我什么时候不应该为引用该特征的实现者实现特征? [英] When should I not implement a trait for references to implementors of that trait?

查看:67
本文介绍了我什么时候不应该为引用该特征的实现者实现特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 trait 和一个接受受约束到该类型的泛型类型的函数,则一切正常.如果我尝试传入对该类型的引用,则会出现编译错误.

If I have a trait, and a function that accepts a generic type constrained to that type, everything works fine. If I try to pass in a reference to that type, I get a compilation error.

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) {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^

我可以通过为任何对实现 trait 的类型的引用实现 trait 来解决这个问题:

I can fix the issue by implementing the trait for any reference to a type that implements the trait:

impl<'a, T> Trait for &'a T
where
    T: Trait,
{
    fn hello(&self) -> u32 {
        (*self).hello()
    }
}

我缺少的一条信息是我何时不应该实施它?换一种方式问,为什么编译器不自动为我实现这个?由于它目前没有,我认为一定有这种实现会不利的情况.

The piece of information that I'm missing is when shouldn't I implement this? Asked another way, why doesn't the compiler automatically implement this for me? Since it currently doesn't, I assume there must be cases where having this implementation would be disadvantageous.

推荐答案

您在此处编写的特定 trait 只需要 self 引用,这是可以编写附加的唯一原因您所做的实施.

The particular trait you are writing here only takes self by reference, and that is the only reason it is possible to write the additional implementation you did.

因此,将参数按值带入runner() 可能是不可取的;你应该参考它.这个指导方针可以普遍适用:如果可以将特征实现为参考,那么而不是想知道我应该实现它吗?"您应该想知道为什么我要实施它??"对于您将使用它的唯一情况,应该首先更改为通过引用获取对象.

For this reason, taking the parameter to runner() by value is probably undesirable; you should instead be taking it by reference. This guideline can apply generally: if it is possible to implement the trait for a reference then rather than wondering "should I implement it?" you should wonder "why would I implement it?" for the only cases where you would use it should probably be altered to take the object by reference in the first place.

这篇关于我什么时候不应该为引用该特征的实现者实现特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆