generic

Rust Trait bounds on type parameters

A bound tells Rust which operations a generic type supports. Use the narrowest capability your algorithm needs; this makes the contract easier to meet. Expected output (not executed): Total: 18 Total: pending Why: Display authorizes the formatting operation in the function body. Common mistake: Expecting an unbounded T to support every operation that a particular caller happens to support.

Formal Syntax & Structure

rust syntaxrust
fn show<T: std::fmt::Display>(value: T)

Working Example

Example Snippetrust
use std::fmt::Display;fn receipt<T: Display>(value: T) { println!("Total: {value}"); }fn main() { receipt(18); receipt("pending"); }
Rust Reference