CodeBlanks Logo Icon CodeBlanks

Trait bound

Constrain a generic parameter with <T: Trait>.

Trait bounds

A trait bound says which behaviours a generic type must have. Writing T: Display lets T values be printed with {} inside the function:

use std::fmt::Display;

fn cerceve<T: Display>(x: T) -> String {
    format!("[{}]", x)
}

println!("{} {}", cerceve(5), cerceve("a"));   // [5] [a]

The bound both permits the function body and restricts the caller: calling with a type that doesn't implement Display is a compile error.

Without a bound

Without a bound the compiler assumes nothing about T, and the error message says what's missing:

fn cerceve<T>(x: T) -> String {
    format!("[{}]", x)
}
// error[E0277]: `T` doesn't implement `std::fmt::Display`
// help: consider restricting type parameter `T`
//   fn cerceve<T: std::fmt::Display>(x: T)

Following the compiler's suggestion is often the fastest way to find the right bound.

Practice Frame it

Write the function fn cerceve<T: Display>(x: T) -> String above. Print the results for 5, "a" and 2.5 on one line separated by spaces.

Starter code

main.rs
use std::fmt::Display;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::fmt::Display;

fn cerceve<T: Display>(x: T) -> String {
    format!("[{}]", x)
}

fn main() {
    println!("{} {} {}", cerceve(5), cerceve("a"), cerceve(2.5));
}

Expected output

[5] [a] [2.5]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why doesn't <code>cerceve(vec![1, 2])</code> compile?

  • It compiles
  • Vec<i32> doesn't implement Display Correct answer
  • Vec can't be generic
  • Two elements is too many

Explanation: Vectors print with {:?} (Debug); {} needs Display, which Vec doesn't implement.

2 Printable

Question
fn cerceve<T: ____>(x: T) -> String {
    format!("[{}]", x)
}
Answer
fn cerceve<T: Display>(x: T) -> String {
    format!("[{}]", x)
}

Explanation: The {} format requires the Display trait.

3 Bound and what it permits

Term Meaning
T: Display Printing with {}
T: Debug Printing with {:?}
T: PartialOrd < and > comparison
T: Clone .clone()

All lessons in Intermediate