Is there a trait supplying `iter()`?

Deadly 提交于 2020-01-02 03:40:28

问题


Is there in Rust a Trait which supplies the iter() method? I only found the trait IntoIterator, which supplies into_inter().

Just to be clear here: I do not want the Iterator trait, which supplies next(), but a trait which supplies iter().

[ sidenote: Sometimes I'm very confused by the Rust libs. Iterator supplies next(), but IntoIterator supplies into_iter() (not supplying next() and for convention with moving), while IntoIter is a struct, that implements the Iterator trait (moving values). ]


回答1:


No, there is no trait that provides iter().

However, IntoIterator is implemented on references to some containers. For example, Vec<T>, &Vec<T> and &mut Vec<T> are three separate types that implement IntoIterator, and you'll notice that they all map to different iterators. In fact, Vec::iter() and Vec::iter_mut() are just convenience methods equivalent to &Vec::into_iter() and &mut Vec::into_iter() respectively.

fn foo(_x: std::slice::Iter<i32>) {}

fn main() {
    let v = vec![1, 2, 3];
    foo(v.iter());
    foo((&v).into_iter()); // iter() exists because this is awkward
}

If you want to write a function that is generic over containers that can be converted into an iterator that iterates over references, you can do so like this:

fn foo<'a, I: IntoIterator<Item=&'a i32>>(_x: I) {}

fn main() {
    let v = vec![1, 2, 3];
    foo(&v);
}


来源:https://stackoverflow.com/questions/39675949/is-there-a-trait-supplying-iter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!