Is there a trait supplying `iter()`?

前端 未结 1 740
礼貌的吻别
礼貌的吻别 2021-02-19 23:09

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

Just to

相关标签:
1条回答
  • 2021-02-20 00:05

    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);
    }
    
    0 讨论(0)
提交回复
热议问题