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?
}
如何转换 Iterator<T>
至 Iterator<U>
并将其传递给另一个函数?
最佳答案
更好的方法是在 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!
}
如果您无法更改函数签名,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()));
}
请注意,在这种情况下,您不能使用 into_iter
,因为没有人会拥有这些字符串。
关于rust - 如何将 Iterator<String> 作为 Iterator<&str> 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55948343/