t6t*_*b7n 3 generics traits rust
我正在尝试实现一个由通用字段组成的结构,该字段的类型必须实现非消耗性“iter”方法(见下文)。
struct Node<T> {
key: T
}
impl<T> Node<T> where T: ?? {
fn do_stuff(&self) {
for e in self.key.iter() {
/* ... */
}
}
}
fn main() {
let n1 = Node { key: "foo".to_owned() };
n1.do_stuff();
let n2 = Node { key: vec![1, 2, 3] };
n2.do_stuff();
}
Run Code Online (Sandbox Code Playgroud)
我应该将哪个特征界限与参数关联起来T?
您正在寻找的特征界限是&T: IntoIterator. 按照惯例,提供非消耗类型的类型也提供foriter()的实现。(同样,与for的 impl 成对出现。)IntoIterator&Titer_mut()IntoIterator&mut T
因此,虽然您无法从字面上调用iter(),但您将能够迭代标准库容器,例如Vec、HashMap等,而无需消耗它们:
impl<T> Node<T>
where
for<'a> &'a T: IntoIterator,
{
fn do_stuff(&self) {
for e in &self.key { /* ... */ }
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,上面的内容不会被接受,key: "foo".to_owned()因为 Rust 字符串不可迭代。