为什么这段代码不起作用?
pub struct Foo {}
impl Foo {
const THREE: i32 = 3;
pub fn mul_three(num: i32) -> i32 {
num * THREE
}
pub fn sub_three(num: i32) -> i32 {
num - THREE
}
}
Run Code Online (Sandbox Code Playgroud)
如果常量向上移动到模块级别或向下移动到函数中,它就会起作用。但是,尽管它在目前的语法上是允许的,但它不可用:
error[E0425]: cannot find value `THREE` in this scope
--> <source>:6:15
|
6 | num * THREE
| ^^^^^ not found in this scope
Run Code Online (Sandbox Code Playgroud)
这背后的技术原因是什么?
您需要在其前面添加Self::(或Foo::) 前缀,因为它是类型的一部分:
pub struct Foo {}
impl Foo {
const THREE: i32 = 3;
pub fn mul_three(num: i32) -> i32 {
num * Self::THREE
}
pub fn sub_three(num: i32) -> i32 {
num - Self::THREE
}
}
Run Code Online (Sandbox Code Playgroud)