在一个新的Rust模块中,我可以写:
struct myStruct {
x : u32
}
impl myStruct {
fn new() -> myStruct{
myStruct{ x : other()}
}
fn other() -> u32 {
6
}
}
来自其他OO语言,我预计new()
的范围将达到other()
.一个类的静态调用与另一个类的静态调用是一样的.然而,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()
来修复它,但这似乎很麻烦.如果我try use myStruct
,我就会得到神秘的信息
7 | use myStruct;
| ^^^ unexpected token
是否总是需要这种明确的范围界定?如果是,为什么?
我做错什么了吗?有没有一个惯用的解决方法?