Generic Function Parameters vs dyn Trait
We have two means of writing polymorphic functions, how do they compare?
// Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0
use std::fmt::Display;
fn print_display(t: &impl Display) {
println!("{}", t);
}
fn print_display_dyn(t: &dyn Display) {
println!("{}", t);
}
fn main() {
// Two functions are generated, each using static dispatch.
print_display(&123);
print_display(&"Hello");
// One function for both input types using dynamic dispatch.
print_display_dyn(&123);
print_display_dyn(&"Hello");
}
-
We can write polymorphic functions over generics or over trait objects.
-
When writing functions with generic parameters, for each unique type that substitutes a parameter a new version of that function is generated.
We went over this in monomorphization: in exchange for binary size, we gain a greater capacity for optimization.
-
When writing functions that take a trait object, only one version of that function will exist in the final binary (not counting inlining.)
-
Generic parameters are zero-cost other than binary size. Types must be homogenous (all instances of T can only be the same type).