[英]Unable to call a function with a reference to a type implementing a trait
I am having some trouble to understand how to work with Traits and ownerships. 我在了解如何使用特征和所有权时遇到了一些麻烦。 The following example works:
以下示例起作用:
struct X([u8; 4]);
impl X {
pub fn get(&self, n: usize) -> u8 {
self.0[n]
}
}
fn f1(x: &X) {
println!("{}", x.get(1));
f2(&x);
}
fn f2(x: &X) {
println!("{}", x.get(2));
}
fn main() {
let z1 = X([1u8, 2u8, 3u8, 4u8]);
f1(&z1);
}
But when I try to create a trait (here XT
) with get
: 但是当我尝试使用
get
创建特征(此处为XT
)时:
trait XT {
fn get(&self, n: usize) -> u8;
}
struct X([u8; 4]);
impl XT for X {
fn get(&self, n: usize) -> u8 {
self.0[n]
}
}
fn f1<T: XT>(x: &T) {
println!("{}", x.get(1));
f2(&x);
}
fn f2<T: XT>(x: &T) {
println!("{}", x.get(2));
}
fn main() {
let z1 = X([1u8, 2u8, 3u8, 4u8]);
f1(&z1);
}
Fails to compile with the following error message: 无法编译以下错误消息:
the trait
XT
is not implemented for the type&T
没有为
&T
类型实现特征XT
It works if I change f2(&x)
to f2(x)
. 它的工作原理,如果我改变
f2(&x)
以f2(x)
My expectation was that replacing the types by the traits, everything will work. 我的期望是,用特征替换类型,一切都会正常。
The problem is that you're trying to pass &&T
to f2
. 问题是您正在尝试将
&&T
传递给f2
。 That means it expects &T
to implement XT
, and that's not what you said: you said that T
implements XT
. 这意味着它期望
&T
实现XT
,但这不是您所说的:您说T
实现了XT
。
You can modify f1
to properly express this constraint by using a where T: XT, for<'a> &'a T: XT
clause, but then you can't call f1
from main
because &X
doesn't implement XT
. 您可以使用
where T: XT, for<'a> &'a T: XT
子句来修改f1
以正确表达此约束,但是由于&X
没有实现XT
,因此您不能从main
调用f1
。 So you go and add an implementation for that as well , and then the code works... but honestly, it's easier to just remove that &
and call f2(x)
instead. 所以,你去添加一个实现该为好 , 然后代码工作......但说实话,它更容易只是删除
&
和调用f2(x)
来代替。
To put it another way: just because a type implements a trait does not mean pointers to that type also implement the trait. 换句话说,仅仅因为类型实现了特征并不意味着指向该类型的指针也实现了特征。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.