Generic structs in Rust
A struct over a type parameter, with impl blocks that can be generic or specific.
struct Pair<T> {
left: T,
right: T,
}
impl<T> Pair<T> {
fn new(left: T, right: T) -> Self {
Pair { left, right }
}
}
impl<T: PartialOrd + std::fmt::Display> Pair<T> {
fn larger(&self) -> &T {
if self.left > self.right {
&self.left
} else {
&self.right
}
}
}
fn main() {
let nums = Pair::new(7, 12);
println!("{}", nums.larger());
println!("{}", Pair::new("fig", "apple").larger());
}
How it works
- The parameter is declared on both the struct and the impl.
- A second impl block can target one concrete type only.
- Methods may add bounds the struct itself does not need.
Keywords and builtins used here
PairPartialOrdSelfTelsefnifimpllargerletmainnewselfstruct
The run, in numbers
- Lines
- 26
- Characters to type
- 386
- Tokens
- 151
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 86 seconds.
Step 3 of 4 in Generics, step 6 of 19 in Traits & generics.