When writing code with traits you can put the trait in a trait bound:
use std::fmt::Debug;
fn myfunction1(v: Box) {
println!(\"
Importantly, you don't have to put the generic type behind a reference (like &
or Box
), you can accept it directly:
fn myfunction3(v: T) {
println!("{:?}", v);
}
fn main() {
myfunction3(5);
}
This has the same benefits of monomorphization without the downside of additional memory allocation (Box
) or needing to keep ownership of the value somewhere (&
).
I would say that generics should often be the default choice — you only require a trait object when there is dynamic dispatch / heterogeneity.