Bounds

When working with generics, the type parameters often must use traits as bounds to stipulate what functionality a type implements. For example, the following example uses the trait Display to print and so it requires T to be bound by Display; that is, T must implement Display.

1. // Define a function `printer` that takes a generic type `T` which
2. // must implement trait `Display`.
3. fn printer<T: Display>(t: T) {
4. println!("{}", t);
5. }

Bounding restricts the generic to types that conform to the bounds. That is:

1. struct S<T: Display>(T);

3. // Error! `Vec<T>` does not implement `Display`. This
4. // specialization will fail.
5. let s = S(vec![1]);

Another effect of bounding is that generic instances are allowed to access the methods of traits specified in the bounds. For example:

1. // A trait which implements the print marker: `{:?}`.
2. use std::fmt::Debug;

4. trait HasArea {
5. fn area(&self) -> f64;
6. }

8. impl HasArea for Rectangle {
9. fn area(&self) -> f64 { self.length * self.height }
10. }

12. #[derive(Debug)]
13. struct Rectangle { length: f64, height: f64 }
14. #[allow(dead_code)]
15. struct Triangle  { length: f64, height: f64 }

17. // The generic `T` must implement `Debug`. Regardless
18. // of the type, this will work properly.
19. fn print_debug<T: Debug>(t: &T) {
20. println!("{:?}", t);
21. }

23. // `T` must implement `HasArea`. Any function which meets
24. // the bound can access `HasArea`'s function `area`.
25. fn area<T: HasArea>(t: &T) -> f64 { t.area() }

27. fn main() {
28. let rectangle = Rectangle { length: 3.0, height: 4.0 };
29. let _triangle = Triangle  { length: 3.0, height: 4.0 };

31. print_debug(&rectangle);
32. println!("Area: {}", area(&rectangle));

34. //print_debug(&_triangle);
35. //println!("Area: {}", area(&_triangle));
36. // ^ TODO: Try uncommenting these.
37. // | Error: Does not implement either `Debug` or `HasArea`.
38. }

As an additional note, where clauses can also be used to apply bounds in some cases to be more expressive.

See also:

std::fmt, structs, and traits