Suppose that I am trying to make a function like:
func(iterator: impl IntoIterator<Item = T>)
I think this works with func(vec)
, but not func(&vec)
, which is fine, but what if I want it to work with both? Assume T
implements Copy
. So I could write two versions of the function,
func_ref(iterator: impl IntoIterator<Item = &T>) {
let vec = iterator.map(|t| *t).collect::<Vec<_>>();
}
func_val(iterator: impl IntoIterator<Item = T>) {
let vec = iterator.collect::<Vec<_>>();
}
But then maybe I would also need a &mut T
version as well, and it feels like it should be able to work for anything that implements Deref<Target = T>
, but I think if I try to define my own trait that’s implemented both for T
and impl Deref<Target = T>
, I’m going to run into the problem that theoretically T
could implement Deref<Target = T>
and so I can’t have conflicting implementations… So I just wonder if there’s a solution to this.
Nicholas Franklin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.