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.into_iter()); // how to pass vec here?
}
How do I convert Iterator<T> to Iterator<U> and pass it to another function?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With