Search⌘ K

Generic Iterator Functions

Explore how to write generic functions that accept any iterator in Rust. Understand trait bounds, associated types, and how to implement functions that work with various iterable types, enhancing your Rust programming skills.

We'll cover the following...

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

Rust 1.40.0
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:

Rust 1.40.0
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 `std::ops::Range`
   |
   = note: expected type `&[_]`
 
...