![](/img/trans.png)
[英]How can I convert a Vec<Option<T>> to an Option<Vec<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.