How to pass Iterator<String> as Iterator<&str>?

自古美人都是妖i 提交于 2021-02-10 05:23:03

问题


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> to Iterator<U> and pass it to another function?

You use the map adapter function of Iterator.


In your particular case, you need to:

  1. use iter instead of into_iter, that makes the vec live longer than the function call
  2. map the Strings 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!