【发布时间】:2015-03-01 21:33:27
【问题描述】:
如果我有一个 trait 和一个接受泛型类型约束的函数,那么一切正常。如果我尝试传入对该类型的引用,则会出现编译错误。
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);
}
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:
<Struct as Trait>
note: required by `runner`
--> src/main.rs:13:1
|
13 | fn runner<T: Trait>(t: T) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^
我可以通过为实现该特征的类型的任何引用实现该特征来解决此问题:
impl<'a, T> Trait for &'a T
where
T: Trait,
{
fn hello(&self) -> u32 {
(*self).hello()
}
}
我缺少的一条信息是我什么时候不应该实现这个?换一种方式问,为什么编译器不自动为我实现这个?由于它目前没有,我认为必须有这种实现是不利的情况。
【问题讨论】: