I am trying and failing to write a trait bound that requires a type to be be deref-able into an iterator that yields items that can be referenced to str:
use std::ops::Deref;
fn main() {
let strings = vec!["hello", "world"];
test(strings);
}
fn test<T>(t: T)
where
T: Deref,
for<'a> &'a T::Target: IntoIterator,
for<'a> <&'a <T as Deref>::Target as IntoIterator>::Item: AsRef<str>,
{
}
Can somebody help me out here?
Why does the above code not work?
It's possible enough to make the type signatures work, here, but one issue that you're going to run into no matter what is that there's a conflict between Deref and IntoIterator. Deref allows an &T to be converted implicitly into an &<T as Deref>::Target, while IntoIerator provides a single method into_iterator(self) — note the lack of &. IntoIterator consumes its input, and Deref doesn't provide you owned access to whatever type you're dereferencing to.
That said, however, from a type-system-only perspective this will compile (though it cannot be executed for the reasons above):
use std::ops::Deref;
fn main() {
let strings = vec!["hello", "world"];
test(&strings);
}
fn test<T, I>(t: T)
where
T: Deref,
T::Target: IntoIterator<Item = I>,
I: AsRef<str>,
{
}