Sub topic 3
Generic structs and enums
This chapter assumes you can define plain structs and enums, match on enums, and write a generic function with a type parameter like fn largest<T>. Here you apply type parameters to data types.
From functions to types
A generic function takes a type parameter. A struct or enum does the same thing. You declare the parameter in angle brackets after the type name, then use it for fields or variants.
#[derive(Debug)]
struct Point<T> {
x: T,
y: T,
}
#[derive(Debug)]
struct Pair<T, U> {
first: T,
second: U,
}
fn main() {
let ints = Point { x: 1, y: 2 };
let floats = Point { x: 1.5, y: 2.5 };
let mixed = Pair { first: "age", second: 42 };
println!("{ints:?} {floats:?} {mixed:?}");
}Point<T> uses one parameter for both fields, so x and y must have the same type. Writing Point { x: 1, y: 2.5 } fails to compile, because T cannot be both an integer and a float. Pair<T, U> uses two parameters, so its fields can differ.
One definition, many concrete types
Point<i32> and Point<f64> are different types. Each one is an instantiation of the same definition with a concrete type filled in. The compiler usually infers the type from the values you pass.
Generic enums
Enums take type parameters the same way. A parameter can appear in some variants and not others. The standard library's two most common enums are generic:
Option<T>has the variantsSome(T)andNone.Result<T, E>has the variantsOk(T)andErr(E).
You can write the same shapes yourself:
#[derive(Debug)]
enum Maybe<T> {
Nothing,
Just(T),
}
#[derive(Debug)]
enum Outcome<T, E> {
Good(T),
Bad(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::Good(n),
Err(e) => Outcome::Bad(e.to_string()),
}
}
fn main() {
println!("{:?}", first_even(&[1, 3, 4]));
println!("{:?}", parse("12"));
println!("{:?}", parse("x"));
}The Nothing variant holds no data, yet Maybe<i32> and Maybe<String> are still different types.
When inference needs help
The compiler cannot guess T when no value mentions it. This line fails with a "type annotations needed" error:
let empty = Maybe::Nothing;Give the compiler the type in either of two ways:
let a: Maybe<i32> = Maybe::Nothing;
let b = Maybe::<i32>::Nothing;A generic wrapper type
Generic structs often wrap a standard collection. The type parameter flows from your struct into the field.
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 main() {
let mut stack = Stack::new();
stack.push("a");
stack.push("b");
println!("{:?}", stack.pop());
}Note impl<T> Stack<T>. The first <T> declares the parameter and the second uses it. The next chapters cover impl blocks in detail. Here, stack.push("a") fixes T as &str for this value.
Common mistakes
- Using one parameter where two types are needed, as in
Point<T>with mixed fields. - Forgetting
impl<T>. Writingimpl Stack<T>treatsTas a real type name, and the compiler reports thatTis not found. - Expecting
Maybe<i32>andMaybe<i64>to be interchangeable. They are separate types.
Exercise
Define a generic struct Wrapper<T> with one field value: T. Then create one Wrapper holding an integer and one holding a String. Why can you not put both in the same Vec?
Show answer
struct Wrapper<T> { value: T } with let a = Wrapper { value: 5 }; and let b = Wrapper { value: String::from("hi") };. A Vec<Wrapper<i32>> holds only one element type, and Wrapper<i32> and Wrapper<String> are different types, so a single Vec cannot hold both.