Iter of values to an iter of references

I have an implementation of a FromIterator of references:

impl<'a> FromIterator<&'a T> for Type<T> {
    fn from_iter<I: IntoIterator<Item = &'a T>>(iter: I) -> Self {
        ...
    }
}

I am trying to implement the non-reference version, without copy-pasting the implementation

impl FromIterator<T> for Type<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self::from_iter(iter.into_iter().????)
    }
}

however, I can't find the API to convert an Iter of values into an Iter of references (can I?). Does anyone knows what should I place on the ?????

The overall idea is to DRY the code of both implementations. In both cases, the implementation only uses references.

I could place the implementation on the iterator of values, and call Self::from_iter(iter.into_iter().cloned()), but that would cause an extra clone per item when the user has an iterator of references.

This isn’t possible in the general case. An &-reference in Rust has to refer to data in some well-defined stack frame, and there isn’t one available to store the values that come out of the source iterator. The closest you can come to this is storing the value on the heap in a Box, Rc, or Arc.


However, in your case you should be able to make the original implementation more generic. Both T and &T implement Borrow<T>, so you should be able to write something like this (untested):

impl<Ptr:Borrow<T>> FromIterator<Ptr> for Type<T> {
    fn from_iter<I: IntoIterator<Item = Ptr>>(iter: I) -> Self {
        ...
    }
}
2 Likes