【发布时间】:2018-09-03 15:29:41
【问题描述】:
在一个新的 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 书中看到任何提及这一点,而且我似乎无法在网上找到明确的答案。我可以通过使用myStruct::other() 明确界定对其他人的调用来修复它,但这似乎很麻烦。如果我尝试use myStruct,我会收到神秘信息
7 | use myStruct;
| ^^^ unexpected token
是否总是需要这种明确的范围界定?如果有,为什么?
我做错了吗?有没有惯用的解决方法?
【问题讨论】:
-
Rust 不像 Java 那样真正是一种“OO”语言。如果你尝试用 Rust 编写 Java,你会遇到很多问题。
-
这与OO语言没有任何关系,这只是一个关于语法的问题。
标签: module rust static-methods