小编Fre*_*reD的帖子

为什么具有 const 泛型布尔值的方法不能调用对 true 和 false 都实现的方法?

此代码完美运行(操场):

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();
}
Run Code Online (Sandbox Code Playgroud)

结果是:

false
true
Run Code Online (Sandbox Code Playgroud)

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

struct MyStruct<const B: bool>;

impl MyStruct<false> {
    pub fn bar() {
        println!("false");
    }
}
impl MyStruct<true> {
    pub fn bar() { …
Run Code Online (Sandbox Code Playgroud)

generics implementation constants rust

3
推荐指数
1
解决办法
56
查看次数

标签 统计

constants ×1

generics ×1

implementation ×1

rust ×1