rust / intermediate
Snippet
Generic Bounds with Traits
Generic bounds allow you to restrict a generic type so that it must implement specific behaviors (traits). This ensures the function can call the required methods safely.
snippet.rs
1
2
3
4
5
6
7
trait Summary {fn summarize(&self) -> String;}fn notify<T: Summary>(item: &T) {println!("Breaking news: {}", item.summarize());}
Breakdown
1
trait Summary {
Defines a trait named Summary.
2
fn notify<T: Summary>(item: &T) {
A function that takes a generic type T, which must implement the Summary trait.