How can I construct and pass an iterator of iterators?

后端 未结 1 1032
逝去的感伤
逝去的感伤 2021-01-17 05:16

I am trying to grok Rust by implementing simple algorithms in it. I managed to make a generic merge_sorted, which ended up having the following signature:

相关标签:
1条回答
  • 2021-01-17 06:01

    Vec::iter borrows the items it contains, so you are iterating over borrowed iterators (&std::slice::Iter) that do not implement Iterator. To consume a vector in order to have the ownership of the items, you must call Vec::into_iter:

    fn main() {
        let v1 = vec![1, 2];
        let vectors = vec![v1.iter()]; // You can use `into_iter` there to iterate over ints.
        merge_sorted(vectors.into_iter());
    }
    

    You can also require IntoIterators that can make easier the usage of your API:

    fn merge_sorted<IterT, IterIterT, T: Ord>(mut arrays: IterIterT) -> Vec<T>
    where
        IterT: IntoIterator<Item = T>,
        IterIterT: IntoIterator<Item = IterT>,
    {
        panic!();
    }
    
    fn main() {
        let v1 = vec![1, 2];
        let vectors = vec![v1];
        merge_sorted(vectors);
    }
    
    0 讨论(0)
提交回复
热议问题