简体   繁体   English

在为引用和非引用类型实现一个特性时,我是否必须实现它两次?

[英]Do I have to implement a trait twice when implementing it for both reference and non-reference types?

I want to implement a trait for both a for reference and non-reference type.我想为引用和非引用类型实现一个特征。 Do I have to implement the functions twice, or this is not idiomatic to do so?我是否必须两次实现这些功能,或者这样做不是惯用的?

Here's the demo code:这是演示代码:

struct Bar {}

trait Foo {
    fn hi(&self);
}

impl<'a> Foo for &'a Bar {
    fn hi(&self) {
        print!("hi")
    }
}

impl Foo for Bar {
    fn hi(&self) {
        print!("hi")
    }
}

fn main() {
    let bar = Bar {};
    (&bar).hi();
    &bar.hi();
}

This is a good example for the Borrow trait.这是Borrow特性的一个很好的例子。

use std::borrow::Borrow;

struct Bar;

trait Foo {
    fn hi(&self);
}

impl<B: Borrow<Bar>> Foo for B {
    fn hi(&self) {
        print!("hi")
    }
}

fn main() {
    let bar = Bar;
    (&bar).hi();
    &bar.hi();
}

No, you do not have to duplicate code.不,您不必复制代码。 Instead, you can delegate:相反,您可以委托:

impl Foo for &'_ Bar {
    fn hi(&self) {
        (**self).hi()
    }
}

I would go one step further and implement the trait for all references to types that implement the trait:我会更进一步,为所有对实现该特性的类型的引用实现该特性:

impl<T: Foo> Foo for &'_ T {
    fn hi(&self) {
        (**self).hi()
    }
}

See also:也可以看看:


&bar.hi();

This code is equivalent to &(bar.hi()) and probably not what you intended.此代码等效于&(bar.hi())并且可能不是您想要的。

See also:也可以看看:

You can use Cow :您可以使用Cow

use std::borrow::Cow;

#[derive(Clone)]
struct Bar;

trait Foo {
    fn hi(self) -> &'static str;
}

impl<'a, B> Foo for B where B: Into<Cow<'a, Bar>> {
    fn hi(self) -> &'static str {
        let bar = self.into();

        // bar is either owned or borrowed:
        match bar {
            Cow::Owned(_) => "Owned",
            Cow::Borrowed(_) => "Borrowed",
        }
    }
}

/* Into<Cow> implementation */

impl<'a> From<Bar> for Cow<'a, Bar> {
    fn from(f: Bar) -> Cow<'a, Bar> {
        Cow::Owned(f)
    }
}

impl<'a> From<&'a Bar> for Cow<'a, Bar> {
    fn from(f: &'a Bar) -> Cow<'a, Bar> {
        Cow::Borrowed(f)
    }
}

/* Proof it works: */

fn main() {
    let bar = &Bar;
    assert_eq!(bar.hi(), "Borrowed");

    let bar = Bar;
    assert_eq!(bar.hi(), "Owned");
}

The one advantage over Borrow is that you know if the data was passed by value or reference, if that matters to you.Borrow相比的一个优势是,您知道数据是通过值还是引用传递,如果这对您很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM