module - 从 Rust 中同一类的另一个静态方法引用静态方法的最佳方法是什么?
问题描述
在一个新的 Rust 模块中,我可以写:
struct myStruct {
x : u32
}
impl myStruct {
fn new() -> myStruct{
myStruct{ x : other()}
}
fn other() -> u32 {
6
}
}
来自其他 OO 语言,我希望other()
在new()
. 也就是说,我希望能够从同一个类的另一个静态方法调用一个类的一个静态方法。但是, rustc 会产生以下消息:
error[E0425]: cannot find function `other` in this scope
--> dummy_module.rs:9:23
|
9 | myStruct{ x : other()}
| ^^^^^ not found in this scope
相反,以下 Java 代码编译得很好:
public class myStruct{
int x;
public myStruct(){
x = other();
}
private int other(){
return 5;
}
}
我不记得在我正在使用的 Rust 书中看到任何提及这一点,而且我似乎无法在网上找到明确的答案。我可以通过使用 显式限定对 other 的调用来修复它myStruct::other()
,但这似乎很麻烦。如果我尝试use myStruct
,那么我会收到神秘的信息
7 | use myStruct;
| ^^^ unexpected token
是否总是需要这种明确的范围界定?如果是这样,为什么?
我做错了什么吗?有一个惯用的解决方法吗?
解决方案
Rust 设计者做出了以下选择:与范围相关的所有内容都是明确的。因此,正如您必须键入self
才能从另一个成员函数调用成员函数:一样,您必须使用:self.foo()
调用静态成员。Self
Self::bar()
我认为是这样,因为self
不能是隐式的:实际上它必须作为参数添加或借用,这与 Java 中this
总是按值获取不同。因此,因为self
已经是一个显式参数,所以需要它作为显式调用者以保持一致性。
由于其内存模型,Rust 显式性允许提供更好的错误消息。例如,考虑以下代码:
struct Struct;
impl Struct {
fn foo(&mut self) {
self.consume();
}
fn consume(self) {}
}
错误信息是:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:5:9
|
5 | self.consume();
| ^^^^ cannot move out of borrowed content
然后团队选择了完全明确性来保持语法的连贯性。
推荐阅读
- r - 使用样本大小、均值和样本方差而不是原始数据点在 r 中格式化数据
- markdown - Markdown:windows路径被视为链接 - 如何防止它?
- postgresql - 具有主键的唯一复合索引
- android - AnimatedVectorDrawable 支持 < 24
- javascript - 您应该将数据附加到 flatlist 还是替换 flatlist 中的数据(flatlist 中重型组件的最佳实践)?
- python - 根据单个特征分解预测
- go - Golang 中 ECDSA 签名验证使用 secp256r1/scep384r1/secp521r1 性能差异
- angular - 无法识别@angular/material?
- javascript - 如何重用在 npm 模块内的 app 模块中创建的 mongoose 连接
- c# - 10m * 0.1m 在 C# 中是否等于 1m?