问题
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?
回答1:
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.
回答2:
How do i convert
Iterator<T>
toIterator<U>
and pass it to another function?
You use the map
adapter function of Iterator
.
In your particular case, you need to:
- use
iter
instead ofinto_iter
, that makes the vec live longer than the function call map
theString
s to&str
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()));
}
playground
来源:https://stackoverflow.com/questions/55948343/how-to-pass-iteratorstring-as-iteratorstr