An even better way would be to write the function in a way such as it doesn't actually care:
fn my_print<T: AsRef<str>>(args: impl Iterator<Item = T>) {
for arg in args {
println!("=> {}", arg.as_ref());
}
}
fn main() {
let vec = vec!["one".to_string(), "two".to_string()];
my_print(vec.into_iter()); // works!
}
If you cannot change the function signature, you have to convert the iterator beforehand:
fn my_print<'a>(args: impl Iterator<Item = &'a str>) {
for arg in args {
println!("=> {}", arg);
}
}
fn main() {
let vec = vec!["one".to_string(), "two".to_string()];
my_print(vec.iter().map(|s| s.as_ref()));
}
Note that in that case you cannot use into_iter
because no-one would own the strings.