First, I wanted a function which would take generic collections but wouldn't consume it. That is, we have a function non_consuming
.
fn non_consuming<'a,I>(_: &'a I)
where &'a I: std::iter::IntoIterator<Item = usize> {}
For specific reasons I'm not able to change the Item
requirement to &usize
. Such the compiler throws an error if I wanted to use this method normally like so:
non_consuming(&vec![0usize,1,2]);
Because IntoIterator
is implemented for &Vec
, but with Item = &T
. Such I had the idea of implementing something like copied but for IntoIterator
instead of Iterator
.
My goal was to create a method into_copied
for any IntoIterator
with Item: &T
which returns a struct C
implementing IntoIterator
with Item: T
and &C
should also implement IntoIterator
with Item: T
.
I use an extension trait to implement into_copied
for any IntoIterator
and the rest of the code is strongly oriented on how copied
was implemented:
pub struct IntoIterCopied<I>
{
into_iter: I,
}
impl<I> IntoIterCopied<I>
{
pub fn new(iter: I) -> Self {
IntoIterCopied{
into_iter: iter,
}
}
}
impl<'a,I,T> IntoIterator for IntoIterCopied<I>
where
I: IntoIterator<Item = &'a T>,
T: 'a + Copy
{
type Item = T;
type IntoIter = std::iter::Copied<I::IntoIter>;
fn into_iter(self) -> Self::IntoIter {
self.into_iter.into_iter().copied()
}
}
pub trait IntoIterCopiedExt {
fn into_copied<'a, T>(self) -> IntoIterCopied<Self>
where
Self: Sized + IntoIterator<Item = &'a T>,
T: 'a + Copy
{
IntoIterCopied::new(self)
}
}
impl<T> IntoIterCopiedExt for T
where T: IntoIterator {}
I thought I could now use the function non_consuming
like so:
let into_iter_adap = (&vec![0usize,1,2]).into_copied();
non_consuming(&into_iter_adap);
However this is the error I got:
error[E0277]: `&IntoIterCopied<&Vec<usize>>` is not an iterator
--> src/main.rs:46:19
|
40 | fn non_consuming<'a,I>(_: &'a I)
| ------------- required by a bound in this
41 | where &'a I: std::iter::IntoIterator<Item = usize>
| ------------------------------------- required by this bound in `non_consuming`
...
46 | non_consuming(&into_iter_adap);
| ^^^^^^^^^^^^^^^ `&IntoIterCopied<&Vec<usize>>` is not an iterator
|
= help: the trait `Iterator` is not implemented for `&IntoIterCopied<&Vec<usize>>`
= note: required because of the requirements on the impl of `IntoIterator` for `&IntoIterCopied<&Vec<usize>>`
I'm not really sure what the error is telling me. I implemented IntoIterator
for IntoIterCopied
but not for &IntoIterCopied
, so why is the note telling me it would be implemented?