The queue attaches an ID to many kinds of things: a page count, a title, later a whole book record. Writing TaggedCount, TaggedTitle and TaggedBook would repeat the same struct and the same methods three times, and every fix would have to be made three times. A generic struct writes the shape once with a placeholder type. struct Tagged<T> has an id and a value of some type T, chosen separately for each value you build.
One value can be a Tagged<u32>, another a Tagged<String>. Within each value the compiler knows the concrete payload type, and it checks every use against it. Behind the scenes, Rust generates a separate copy of the code for each concrete type you use. This is called monomorphization, and it means generic code runs as fast as code written by hand for each type.
impl<T> Tagged<T> declares T for the impl block and uses it in the type being implemented, so the methods exist for every payload type. Returning &T from a method borrows the existing payload instead of moving it out.
Predict and run
What type is the payload of each value? Does calling value move either payload?
struct Tagged<T> {
id: u32,
value: T,
}
impl<T> Tagged<T> {
fn value(&self) -> &T {
&self.value
}
}
fn main() {
let count = Tagged { id: 1, value: 42 };
let title = Tagged { id: 2, value: String::from("Rust") };
println!("#{} {}", count.id, count.value());
println!("#{} {}", title.id, title.value());
}Check your prediction
#1 42
#2 RustRust infers T from the field value: count is a Tagged<i32>, because an integer literal with no other hint is i32, and title is a Tagged<String>. value takes &self and returns a reference, so neither payload moves. Try adding let done = Tagged { id: 3, value: true }; and calling done.value(). Predict whether you need any new code.
One type per value
T is fixed when a value is created. After that, the field accepts only that type. Writing count.value = true; (with count declared mut) fails with error[E0308]: mismatched types, "expected integer, found bool". A Tagged<i32> and a Tagged<bool> are different types, as different as i32 and bool.
An impl block can also name a concrete type instead of T. Its methods then exist only for that one payload type:
struct Tagged<T> {
id: u32,
value: T,
}
impl<T> Tagged<T> {
fn into_value(self) -> T {
self.value
}
}
impl Tagged<String> {
fn title_len(&self) -> usize {
self.value.len()
}
}
fn main() {
let title = Tagged { id: 2, value: String::from("Rust Patterns") };
println!("#{} has {} characters", title.id, title.title_len());
let owned: String = title.into_value();
println!("Took out: {owned}");
let pages = Tagged { id: 3, value: 320 };
println!("Took out: {}", pages.into_value());
}#2 has 13 characters
Took out: Rust Patterns
Took out: 320into_value takes self by value, so it consumes the wrapper and hands back the payload, whatever its type. title_len exists only on Tagged<String>: calling pages.title_len() fails with error[E0599]: no method named title_len found for struct Tagged<{integer}>. (len counts bytes, which equals characters for plain English text like this.)
What a generic body may not assume
Inside impl<T>, the code must work for every possible T, including types that cannot be printed, compared or copied. So this fails:
impl<T> Tagged<T> {
fn describe(&self) {
println!("#{} {}", self.id, self.value);
}
}The error is error[E0277]: T doesn't implement std::fmt::Display. The method never said that T can be displayed, and for some T it cannot. Returning &T and moving T are fine, because every type supports those. To do more, you add a requirement on T, called a trait bound, which is the next lesson.
Make it generic when the code does not care
A struct is a good candidate for a type parameter when its methods only store, borrow or return the payload. If every method needs something specific from the payload, that is where a trait bound comes in.
Practice
Your turn
Define Pair<T> with two fields of the same type, first and second. Give it a first method that borrows the first value and a swap(self) -> Pair<T> method that returns the values in the other order. Use it with the numbers 7 and 12 and with the titles Rust and Testing. Expected output: 7 before 12, Rust before Testing, Testing before Rust.
fn main() {
// Construct a number pair and a text pair.
}Hint 1: the idea
A single type parameter on both fields requires them to agree for each Pair. Neither method needs to know what the type is.
Hint 2: a first step
Write struct Pair<T> { first: T, second: T }, then an impl<T> Pair<T> block. swap can build Pair { first: self.second, second: self.first }.
Worked solution
struct Pair<T> {
first: T,
second: T,
}
impl<T> Pair<T> {
fn first(&self) -> &T {
&self.first
}
fn swap(self) -> Pair<T> {
Pair { first: self.second, second: self.first }
}
}
fn main() {
let numbers = Pair { first: 7, second: 12 };
let topics = Pair { first: String::from("Rust"), second: String::from("Testing") };
println!("{} before {}", numbers.first(), numbers.second);
println!("{} before {}", topics.first(), topics.second);
let swapped = topics.swap();
println!("{} before {}", swapped.first(), swapped.second);
}7 before 12
Rust before Testing
Testing before Rustswap moves both fields into the new Pair, so it works for String without copying any text, and topics cannot be used afterward. Pair { first: 7, second: String::from("x") } would not compile, because both fields share one T. A field and a method may share the name first; the parentheses decide which one you mean.
Completion is saved in this browser only. It does not measure mastery.