We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
Generics and Traits
RustWrite reusable functions and types with generics, trait bounds and associated types. Learn to read and express the requirements of an API.
This track uses Rust. You can make it your practice mode to browse related content across the site.
Your learning sequence
- 1 Not solved yet. Traits as shared behaviour Practice · Easy
- 2 Not solved yet. Select type arguments with a turbofish Practice · Easy
- 3 Not solved yet. Trait bounds and why f64 is not Ord Practice · Easy
- 4 Not solved yet. where clauses and the bound you cannot write inline Practice · Easy
- 5 Not solved yet. Build a generic stack with conditional methods Practice · Medium
- 6 Not solved yet. Format money with Display Practice · Easy
- 7 Equality, ordering and hashing: keeping traits consistent Read
- 8 Not solved yet. Supertraits and default methods Practice · Medium
- 9 Not solved yet. Convert temperatures with From and Into Practice · Medium
- 10 Not solved yet. TryFrom and TryInto: validate a percentage Practice · Medium
- 11 Not solved yet. Accept string-like values with AsRef Practice · Medium
- 12 Not solved yet. Expose a string view with Deref Practice · Medium
- 13 Not solved yet. Choose the intended method through a wrapper Practice · Medium
- 14 How Rust chooses a method Read
- 15 Not solved yet. Operator overloading: + is just a trait method Practice · Medium
- 16 Not solved yet. Associated type or generic parameter? Practice · Hard
- 17 Not solved yet. Named generics and impl Trait parameters Practice · Medium
- 18 Not solved yet. Returning impl Trait, and what edition 2024 changed Practice · Hard
- 19 Not solved yet. Blanket implementations: shared behavior and overlap Practice · Hard
- 20 Not solved yet. Implementing traits with a newtype Practice · Hard
- 21 Not solved yet. Extension traits: adding methods to types you do not own Practice · Medium
- 22 Not solved yet. Sealed traits: public to use, closed to implement Practice · Medium
- 23 Traits with no methods: Copy, Sized, Send, Sync Read
- 24 When derived trait bounds are too restrictive Read
Check yourself
4 questions · not saved while you're signed outUse these questions to check your understanding and compare explanations. Your score does not affect track completion.
Why can chosen return different iterator types from its two branches, while fixed returns one hidden type?
Choose one answer to reveal the explanations. Answers are kept only while this page is open.
fn fixed() -> impl Iterator<Item = u8> {
0..3
}
fn chosen(reverse: bool) -> Box<dyn Iterator<Item = u8>> {
if reverse {
Box::new((0..3).rev())
} else {
Box::new(0..3)
}
}
fn main() {
println!("{:?}", fixed().collect::<Vec<_>>());
println!("{:?}", chosen(true).collect::<Vec<_>>());
}