“该特征不是为自我实现的”,尽管它完全是

use*_*762 2 rust

看看这个小片段:

pub trait TestTrait {
    fn test_function(&self) {
        generic_function(self);
    }   
}

fn generic_function<T : TestTrait> (x : T) {
    //do something
}
Run Code Online (Sandbox Code Playgroud)

这会产生以下错误消息:

error[E0277]: the trait bound `&Self: TestTrait` is not satisfied
  --> src\main.rs:10:26
   |
10 |         generic_function(self);
   |         ---------------- ^^^^ the trait `TestTrait` is not implemented for `&Self`
   |         |
   |         required by a bound introduced by this call
   |
note: required by a bound in `generic_function`
  --> src\main.rs:14:25
   |
14 | fn generic_function<T : TestTrait> (x : T) {
   |                         ^^^^^^^^^ required by this bound in `generic_function`
Run Code Online (Sandbox Code Playgroud)

但这没有任何意义。这test function是与 Trait 相关的方法TestTrait。当然,自我将实现这个特征,这就是重点!

这是怎么回事?如何使这项工作有效?

小智 5

generic_function按值获取对象。该函数test_function获取对 的引用self但不拥有,self因此无法self按值赋予generic_function

有 2 个简单的修复方法。请注意,两者都需要约束TestTrait where Self: Sized

1:generic_function通过引用获取参数

pub trait TestTrait where Self: Sized {
    fn test_function(&self) {
        generic_function(self);
    }   
}

fn generic_function<T : TestTrait> (x : &T) {
    //do something
}
Run Code Online (Sandbox Code Playgroud)
  1. test_functionself价值取值
pub trait TestTrait where Self: Sized {
    fn test_function(self) {
        generic_function(self);
    }   
}

fn generic_function<T : TestTrait> (x : T) {
    //do something
}
Run Code Online (Sandbox Code Playgroud)