[英]Rust: "the trait is not implemented for Self" even though it totally is
Look at this little snippet:看看这个小片段:
pub trait TestTrait {
fn test_function(&self) {
generic_function(self);
}
}
fn generic_function<T : TestTrait> (x : T) {
//do something
}
This produces this error message:这会产生以下错误消息:
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`
But this doesn't make any sense.但这没有任何意义。 The test function
is a method associated with the trait TestTrait
. test function
是与特征TestTrait
关联的方法。 Of course, the self is going to implement this trait, that's the entire point!当然,self 会实现这个 trait,这就是重点!
What's going on?这是怎么回事? How to make this work?如何使这项工作?
generic_function
takes an object by value. generic_function
按值获取 object。 The function generic_function
gets a reference to self
and does not own self
so is not able to give self
by value to generic_function
. function generic_function
获得对self
的引用并且不拥有self
因此无法将self
按值赋予generic_function
。
There are 2 simple fixes.有 2 个简单的修复。 Note that both require the constrain TestTrait where Self: Sized
.请注意,两者都需要约束TestTrait where Self: Sized
。
1: generic_function
takes the argument by reference 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
}
test_function
takes self
by value test_function
按值self
pub trait TestTrait where Self: Sized {
fn test_function(self) {
generic_function(self);
}
}
fn generic_function<T : TestTrait> (x : T) {
//do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.