繁体   English   中英

如何结合 Vec 的特征实现<t>以及 Vec&lt;&amp;T&gt;</t>

[英]How can I combine implementations of a trait for Vec<T> as well as Vec<&T>

我有一个我拥有的特质:

trait Reducer {
  fn reduce(&self) -> Res;
}

我想针对以下情况实施:

struct MyStruct {... fields ...}

impl Reducer for Vec<MyStruct> {
  fn reduce(&self) -> Res { ... some implementation ... }
}

我想以尽可能便宜的价格(不重复代码等)获取 Vec 中对象的引用:

例如:

// I want this please:

impl Reducer for Vec<&MyStruct> {
  // it's the same implementation as before
}

我应该如何更改我的impl签名以满足这两种情况?

如果您的 reducer 只需要迭代Vec中的项目,那么Vec<T>Vec<&T>之间没有区别,因为两者都可以轻松地在&T上生成迭代器。 例如:

// actual implementation
fn reduce_it<'a>(_items: impl Iterator<Item = &'a MyStruct>) -> Res {
    todo!()
}

impl Reducer for Vec<MyStruct> {
    fn reduce(&self) -> Res {
        reduce_it(self.iter())
    }
}

impl Reducer for Vec<&MyStruct> {
    fn reduce(&self) -> Res {
        reduce_it(self.iter().copied())
    }
}

操场

使用Borrow特征,您可以概括所有可以作为&MyStruct借用的类型(尤其包括MyStruct&MyStruct ):

use std::borrow::Borrow;

trait Reducer {
  fn reduce(&self) -> Res;
}

struct MyStruct;
struct Res;

impl<T: Borrow<MyStruct>> Reducer for Vec<T> {
    fn reduce(&self) -> Res {
        for t in self {
            let _t: &MyStruct = t.borrow();
            // do something with `_t`
        }
        Res
    }
}

fn main() {
    let v: Vec<MyStruct> = vec![];
    let v_ref: Vec<&MyStruct> = vec![];

    // fully qualified because it gets mangled with `Iterator::reduce` otherwise.
    Reducer::reduce(&v);
    Reducer::reduce(&v_ref);
}

暂无
暂无

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

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