Trait Bounds On Generic Functions
Write one implementation for many types with trait bounds: T: Display for printing, a custom trait for domain behavior, and impl Trait to keep signatures short.
Code
use std::fmt::Display;
// 标准库 trait bound:任何可显示的类型都能打印
fn dump_all<T: Display>(items: &[T], label: &str) {
let joined = items.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ");
println!("{label}: {joined}");
}
// 自定义 trait 承载领域行为,而不是依赖某个具体类型
trait Shippable {
fn weight_kg(&self) -> f64;
}
struct Parcel { kg: f64 }
struct Pallet { parcels: u32, kg_each: f64 }
impl Shippable for Parcel {
fn weight_kg(&self) -> f64 { self.kg }
}
impl Shippable for Pallet {
fn weight_kg(&self) -> f64 { self.parcels as f64 * self.kg_each }
}
// impl Trait 是 <T: Trait> 的简写:签名更短,能力相同
fn total_weight(items: &[impl Shippable]) -> f64 {
items.iter().map(|i| i.weight_kg()).sum()
}
fn main() {
dump_all(&[1, 22, 333], "numbers");
dump_all(&["go", "rust"], "langs");
let parcels = [Parcel { kg: 2.5 }, Parcel { kg: 4.0 }];
let pallets = [Pallet { parcels: 4, kg_each: 12.0 }];
println!("parcels total: {:.1} kg", total_weight(&parcels));
println!("pallets total: {:.1} kg", total_weight(&pallets));
}Inside the snippet
The working surface is the functions dump_all, weight_kg, total_weight and main — everything else is wiring.
Putting it to use
The demo output is labeled (parcels total:, pallets total:), so every printed line maps back to its originating operation.
main sequences dump_all and total_weight; executing the file runs that flow once.
Core lines
items.iter().map(|i| i.weight_kg()).sum()
}
let joined = items.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ");
fn weight_kg(&self) -> f64 { self.parcels as f64 * self.kg_each }
Interactive Tools for This Topic
FAQ
- What does Trait Bounds On Generic Functions print when run?
- Execute the whole file; each printed line is prefixed with a label like `parcels total:`, `pallets total:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.