简体   繁体   English

我可以创建一个既可以使用值也可以使用对特征的借用引用的结构?

[英]Can I make a struct that works with both values and borrowed references to a trait?

I want to make a struct that wraps another type but can take both owned and borrowed version of values that implement a given trait. 我想创建一个包装另一种类型的结构,但可以采用实现给定特征的自有和借用版本的值。

For example, let's say I have the trait Foobar : 例如,假设我有特性Foobar

trait Foobar {
    fn foobar(&self);
}

I now want to make a struct that wraps values or borrowed references of this trait: 我现在想要创建一个包含值或借用此特征引用的结构:

struct FoobarWrapper<T: Foobar> {
    wrapped: T,
    extra_stuff: Stuff
}

Here, I want FoobarWrapper to work with both Baz and &Baz given that impl Foobar for Baz . 在这里,我希望FoobarWrapper能够同时使用Baz&Baz因为它可以impl Foobar for Baz提供impl Foobar for Baz

I have come up with one solution that might work but I don't know if it's idiomatic and that's to simply do: 我想出了一个可行的解决方案,但我不知道它是否是惯用的,而且只是这样做:

impl<'a, T: Foobar> Foobar for &'a T  {
    fn foobar(&self) {
        (*self).foobar()
    }
}

If I'm not mistaken, this makes any reference to a value that implements Foobar also an implementor of Foobar. 如果我没有弄错的话,这就引用了一个实现Foobar的值,也是Foobar的实现者。 But is this the way you're supposed to do it? 但这是你应该这样做的吗?

Yes, your solution is probably fine if you can support it. 是的,如果你能支持它,你的解决方案可能会很好。 Iterator does the same thing with Iterator做同样的事情

impl<'a, I> Iterator for &'a mut I where I: Iterator + ?Sized

You should probably also add the ?Sized bound too, for flexibility. 您也应该添加?Sized界限,以获得灵活性。

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

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