Joh*_*tte 2 static-methods module rust
在一个新的Rust模块中,我可以写:
struct myStruct {
x : u32
}
impl myStruct {
fn new() -> myStruct{
myStruct{ x : other()}
}
fn other() -> u32 {
6
}
}
Run Code Online (Sandbox Code Playgroud)
来自其他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
Run Code Online (Sandbox Code Playgroud)
相比之下,以下Java代码编译良好:
public class myStruct{
int x;
public myStruct(){
x = other();
}
private int other(){
return 5;
}
}
Run Code Online (Sandbox Code Playgroud)
我不记得在我正在使用的Rust书中看到任何提及这一点,我似乎无法在网上找到明确的答案.我可以通过显式确定对其他人的调用来修复它myStruct::other()
,但这看起来很麻烦.如果我尝试use myStruct
,那么我得到了神秘的信息
7 | use myStruct;
| ^^^ unexpected token
Run Code Online (Sandbox Code Playgroud)
是否总是需要明确的范围界定?如果是这样,为什么?
我做错了吗?这有一个惯用的解决方法吗?
是的,它是有意的,因为 Rust 不是 Java ;)
你可以这样写:
myStruct { x: myStruct::other() }
Run Code Online (Sandbox Code Playgroud)
或者
myStruct { x: Self::other() }
Run Code Online (Sandbox Code Playgroud)
我无法告诉您确切的设计决策,为什么Self
不自动导入函数,但是您可以通过使用正确的路径来“解决”这个问题。
Rust设计师做出了以下选择:与范围相关的所有内容都是明确的.因此,正如您必须键入self
以从另一个成员函数self.foo()
调用成员函数:,您必须使用Self
:调用静态成员Self::bar()
.
我认为情况就是这样,因为self
不能隐含:实际上它必须通过值或借用作为参数添加,而不像Java那样this
总是按值进行.因此,因为self
它已经是一个显式参数,所以需要它作为一致性的显式调用者.
由于其内存模型,Rust expliciteness允许提供更好的错误消息.例如,考虑以下代码:
struct Struct;
impl Struct {
fn foo(&mut self) {
self.consume();
}
fn consume(self) {}
}
Run Code Online (Sandbox Code Playgroud)
错误消息是:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:5:9
|
5 | self.consume();
| ^^^^ cannot move out of borrowed content
Run Code Online (Sandbox Code Playgroud)
然后团队选择了完整的语法来保持语法的连贯性.
归档时间: |
|
查看次数: |
871 次 |
最近记录: |