7
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?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
amin
  • 3,672
  • 5
  • 33
  • 61

2 Answers2

11

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.

hellow
  • 12,430
  • 7
  • 56
  • 79
mcarton
  • 27,633
  • 5
  • 85
  • 95
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

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
chpio
  • 896
  • 6
  • 16