【问题标题】:Why can a method with a const generic boolean not call a method that is implemented for both true and false?为什么具有 const 泛型布尔值的方法不能调用为真假都实现的方法?
【发布时间】:2021-10-31 00:35:46
【问题描述】:

这段代码完美运行(playground):

struct MyStruct<const B: bool>;

impl MyStruct<false> {
    pub fn bar() {
        println!("false");
    }
}
impl MyStruct<true> {
    pub fn bar() {
        println!("true");
    }
}

impl MyStruct<false> {
    pub fn foo() {
        MyStruct::<false>::bar()
    }
}
impl MyStruct<true> {
    pub fn foo() {
        MyStruct::<true>::bar()
    }
}

fn main() {
    MyStruct::<false>::foo();
    MyStruct::<true>::foo();
}

结果:

false
true

另一方面,此代码将失败 (playground):

struct MyStruct<const B: bool>;

impl MyStruct<false> {
    pub fn bar() {
        println!("false");
    }
}
impl MyStruct<true> {
    pub fn bar() {
        println!("true");
    }
}

impl<const B: bool> MyStruct<B> {
    pub fn foo() {
        MyStruct::<B>::bar()
    }
}

fn main() {
    MyStruct::<false>::foo();
    MyStruct::<true>::foo();
}

导致:

error[E0599]: no function or associated item named `bar` found for struct `MyStruct<B>` in the current scope
  --> src/main.rs:16:24
   |
1  | struct MyStruct<const B: bool>;
   | ------------------------------- function or associated item `bar` not found for this
...
16 |         MyStruct::<B>::bar()
   |                        ^^^ function or associated item not found in `MyStruct<B>`
   |
   = note: the function or associated item was found for
           - `MyStruct<false>`
           - `MyStruct<true>`

对于无限值类型,我可以理解这个错误,但为什么是布尔值?

有没有办法克服这个问题?

【问题讨论】:

    标签: generics rust constants implementation


    【解决方案1】:

    必须使用 trait 和泛型类型条件 (playground):

    struct MyStruct<const B: bool>;
    
    trait Bar {
        fn bar();
    }
    
    impl Bar for MyStruct<false> {
        fn bar() {
            println!("false");
        }
    }
    impl Bar for MyStruct<true> {
        fn bar() {
            println!("true");
        }
    }
    
    impl<const B: bool> MyStruct<B>
    where
        MyStruct<B>: Bar,
    {
        pub fn foo() {
            MyStruct::<B>::bar()
        }
    }
    
    fn main() {
        MyStruct::<false>::foo();
        MyStruct::<true>::foo();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 2016-12-26
      相关资源
      最近更新 更多