Sub topic 3
Generic structs and enums
This chapter assumes you know basic Rust syntax, ownership and borrowing with &T, how to implement a trait, and how to use Option, Result, and Vec. It also assumes you have seen a generic function such as fn largest<T: PartialOrd>(items: &[T]) -> &T. Here the same idea moves from functions to data types.
Type parameters on data types
A generic struct declares one or more type parameters in angle brackets after its name. Each parameter then stands in for a real type in the field definitions.
#[derive(Debug)]
struct Point<T> {
x: T,
y: T,
}
#[derive(Debug)]
struct Mixed<T, U> {
x: T,
y: U,
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = Point { x: 1.5, y: 2.5 };
let c = Mixed { x: 1, y: 2.5 };
println!("{a:?} {b:?} {c:?}");
}Point<T> uses one parameter for both fields, so x and y must have the same type. Mixed<T, U> allows them to differ. The compiler infers the parameters from the values you pass, so a becomes Point<i32> and b becomes Point<f64>.
Each instantiation is a separate type. Point<i32> and Point<f64> share a definition but are not interchangeable, and you cannot pass one where the other is expected.
use std::mem::size_of;
struct Point<T> {
x: T,
y: T,
}
fn main() {
println!("Point<u8>: {} bytes", size_of::<Point<u8>>());
println!("Point<f64>: {} bytes", size_of::<Point<f64>>());
}On common platforms this prints 2 and 16. Each instantiation gets its own layout, sized for the concrete type. That is why the compiler needs to know every type parameter by the end of type checking.
Generic enums
Enums take type parameters the same way. The standard library's Option<T> and Result<T, E> are ordinary generic enums, defined essentially like this:
enum Option<T> {
None,
Some(T),
}
enum Result<T, E> {
Ok(T),
Err(E),
}You can write your own. A parameter does not have to appear in every variant. None carries no data, yet it still belongs to Option<T>, and its T is fixed by context.
#[derive(Debug)]
enum Maybe<T> {
Nothing,
Just(T),
}
#[derive(Debug)]
enum Outcome<T, E> {
Success(T),
Failure(E),
}
fn first_even(values: &[i32]) -> Maybe<i32> {
for &v in values {
if v % 2 == 0 {
return Maybe::Just(v);
}
}
Maybe::Nothing
}
fn parse(s: &str) -> Outcome<i32, String> {
match s.parse::<i32>() {
Ok(n) => Outcome::Success(n),
Err(e) => Outcome::Failure(e.to_string()),
}
}
fn main() {
println!("{:?}", first_even(&[1, 3, 4]));
println!("{:?}", first_even(&[1, 3]));
println!("{:?}", parse("42"));
println!("{:?}", parse("x"));
}In first_even, the return type tells the compiler that Maybe::Nothing is a Maybe<i32>. Without that context, a bare Maybe::Nothing would leave T unknown.
Inference, annotations, and the turbofish
The compiler infers type parameters from three sources: the values you construct, later uses of the variable, and the expected type at the use site. When none of these determine a parameter, you must supply it.
fn main() {
let empty: Vec<i32> = Vec::new();
let bytes = Vec::<u8>::new();
let mut names = Vec::new();
names.push("ada");
let n = "42".parse::<i64>().unwrap();
println!("{} {} {:?} {}", empty.len(), bytes.len(), names, n);
}let empty: Vec<i32>annotates the variable.Vec::<u8>::new()andparse::<i64>()use the turbofish, the::<...>syntax, to give the parameter directly.namesneeds no annotation, because the later call topush("ada")fixesTas&str.
Common errors
Mixing types in a single-parameter struct. Point { x: 1, y: 2.0 } does not compile. T was already fixed as an integer by x, and 2.0 is a float. The error reads "mismatched types". The fix is either to make both values the same type or to declare Point<T, U>.
Recursive types without indirection. A generic enum that contains itself has infinite size unless you place the recursion behind a pointer such as Box.
#[derive(Debug)]
enum List<T> {
Cons(T, Box<List<T>>),
Nil,
}
use List::{Cons, Nil};
fn main() {
let list = Cons(1, Box::new(Cons(2, Box::new(Nil))));
println!("{list:?}");
}Without the Box, the compiler reports "recursive type has infinite size" (E0072). With it, each Cons holds a fixed-size pointer.
Unused type parameters. If you declare struct Tag<T> { id: u32 }, the compiler rejects it with "parameter T is never used" (E0392). Every type parameter must appear in a field. The standard fix, PhantomData, is covered in a later chapter.
Bounds on type definitions
You can write a bound on a struct, as in struct Wrapper<T: Display> { value: T }. Usually you should not. A bound on the definition forces every use of the type, including every impl block, to repeat it, and it rarely gives you anything in return. Put bounds on the impl blocks and functions that need them.
Deriving traits does not conflict with this. #[derive(Debug)] on Point<T> generates impl<T: Debug> Debug for Point<T>, so Point<T> implements Debug only when T does. The same applies to Clone, PartialEq, and the other derivable traits. A Point<NotDebug> can exist, but you cannot print it.
A generic wrapper over existing generics
Generic types often wrap other generic types. A stack backed by Vec<T> keeps the same T and adds a narrower interface:
struct Stack<T> {
items: Vec<T>,
}
impl<T> Stack<T> {
fn new() -> Self {
Stack { items: Vec::new() }
}
fn push(&mut self, item: T) {
self.items.push(item);
}
fn pop(&mut self) -> Option<T> {
self.items.pop()
}
fn peek(&self) -> Option<&T> {
self.items.last()
}
fn len(&self) -> usize {
self.items.len()
}
}
fn main() {
let mut stack = Stack::new();
stack.push("a");
stack.push("b");
println!("{:?} {}", stack.peek(), stack.len());
println!("{:?}", stack.pop());
println!("{:?}", stack.pop());
println!("{:?}", stack.pop());
}Three details are worth noting:
impl<T>declaresTfor the block. Without that first<T>, Rust would look for a concrete type namedT.popreturnsOption<T>, which gives ownership of the item to the caller.peekreturnsOption<&T>, which only borrows it.Stack::new()leavesTopen untilpush("a")fixes it as&str.
The next chapters cover impl blocks in more detail, including blocks that apply only to one instantiation, such as impl Stack<String>.
Summary table
| Situation | What to write |
|---|---|
| Both fields share a type | `struct Point<T> { x: T, y: T }` |
| Fields may differ | `struct Mixed<T, U> { x: T, y: U }` |
| Variants carry different data | `enum Outcome<T, E> { Success(T), Failure(E) }` |
| Compiler cannot infer | `Vec::<u8>::new()` or `let v: Vec<u8>` |
| Type contains itself | Wrap the recursive part in `Box<...>` |
| Type needs a trait | Put the bound on the `impl`, not the struct |
Exercise
The code struct Pair<T> { a: T, b: T } followed by let p = Pair { a: 1, b: "one" }; fails to compile. Explain why, then show two different ways to fix it without changing the values 1 and "one".
Show answer
Pair<T> has a single type parameter, so a and b must have the same type. Here a is an integer and b is a &str, which gives a "mismatched types" error. Fix 1: give the struct two parameters, struct Pair<T, U> { a: T, b: U }, so p becomes Pair<i32, &str>. Fix 2: make both fields the same type by converting one value, for example Pair { a: 1.to_string(), b: "one".to_string() }, which gives Pair<String>.
Exercise
Define a generic enum Either<L, R> with variants Left(L) and Right(R). Write a function describe(e: Either<i32, String>) -> String that returns "number 5" for Left(5) and "text hi" for Right("hi".to_string()).
Show answer
enum Either<L, R> { Left(L), Right(R) }
fn describe(e: Either<i32, String>) -> String {
match e {
Either::Left(n) => format!("number {n}"),
Either::Right(s) => format!("text {s}"),
}
}
The enum is generic, but describe fixes L as i32 and R as String, so the match arms can use n and s as concrete values.