Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 720
amin Avatar asked Jul 18 '26 23:07

amin


1 Answers

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.

like image 90
mcarton Avatar answered Jul 21 '26 23:07

mcarton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!