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:
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);
}