【问题标题】:Why can't you put constants in an impl block?为什么不能将常量放在 impl 块中?
【发布时间】:2023-01-22 17:55:04
【问题描述】:

为什么这段代码不起作用?

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
    }
}

Compiler Explorer link

如果将常量向上移动到模块级别或向下移动到函数中,它就会起作用。但是,尽管它在当前的位置在语法上是允许的,但它不可用:

error[E0425]: cannot find value `THREE` in this scope
 --> <source>:6:15
  |
6 |         num * THREE
  |               ^^^^^ not found in this scope

这背后的技术原因是什么?

【问题讨论】:

    标签: rust


    【解决方案1】:

    您需要在它前面加上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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 2010-09-27
      • 2013-06-09
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多