...

/

Generic Iterator Functions

Generic Iterator Functions

We'll cover the following...

Let’s write a function that will print out each value in a slice:

Press + to interact
use std::fmt::Display;
fn print_them_all<T: Display>(slice: &[T]) {
for x in slice {
println!("{}", x);
}
}
fn main() {
print_them_all(&[1, 1, 2, 3, 5, 8, 13]);
}

But this function is a bit limiting. For example, even though the for loop inside print_them_all is happy to work on a range expression, we can’t use our function that way. In other words, this main function:

Press + to interact
fn main() {
print_them_all(1..11);
}

will result in the error message:

error[E0308]: mismatched types
  --> src/main.rs:10:20
   |
10 |     print_them_all(1..11);
   |                    ^^^^^ expected &[_], found struct
...