Generic functions and structs
Quick answer
Generics allow code to work with multiple types while preserving static type checking. Use a type parameter when an operation or container does not require one concrete type.
Type parameters
Declare fn name<T>(value: T) or struct Name<T>. A parameter can be inferred from arguments or specified with ::<Type>. With no trait bounds, generic code can move or borrow its value but cannot assume it supports operations such as arithmetic.
fn identity<T>(value: T) -> T { value }fn main() { println!("{} {}", identity(7), identity("hi")); }Expected stdout (not executed):
7 hiEach call infers a different concrete T.
struct Pair<T, U> { left: T, right: U }fn main() { let pair = Pair { left: "count", right: 3 }; println!("{}: {}", pair.left, pair.right);}Expected stdout (not executed):
count: 3Two type parameters allow different field types.
Common mistake
Using one T for two fields requires both fields to have the same type.
Try it yourself
Create a generic container for a value and a boolean validity flag.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic functions and structs — practice quiz
Choose one answer per question, then review the explanation.
What does `fn identity<T>(x: T) -> T { x }` do?
How can you explicitly instantiate identity with u32?
Can a generic struct `Pair<T> { a: T, b: T }` hold an i32 and bool in separate fields directly?