相关疑难解决方法(0)

什么时候我不应该实现引用该特征的实现者的特征?

如果我有一个特征,并且接受一个约束到该类型的泛型类型的函数,一切正常.如果我尝试传入对该类型的引用,我会收到编译错误.

trait Trait {
    fn hello(&self) -> u32;
}

struct Struct(u32);

impl Trait for Struct {
    fn hello(&self) -> u32 {
        self.0
    }
}

fn runner<T: Trait>(t: T) {
    println!("{}", t.hello())
}

fn main() {
    let s = Struct(42);

    // Works
    runner(s);

    // Doesn't work
    runner(&s);
}
Run Code Online (Sandbox Code Playgroud)
error[E0277]: the trait bound `&Struct: Trait` is not satisfied
  --> src/main.rs:24:5
   |
24 |     runner(&s);
   |     ^^^^^^ the trait `Trait` is not implemented for `&Struct`
   |
   = help: the following implementations were found: …
Run Code Online (Sandbox Code Playgroud)

reference traits rust

15
推荐指数
2
解决办法
1534
查看次数

标签 统计

reference ×1

rust ×1

traits ×1