By the end of this lesson
Describe one operation for several element types.
Before you start
- Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
- Complete lesson 20, or be comfortable explaining and running its examples.
Three words to know
- Generic parameter
- A placeholder type such as T.
- Concrete type
- The actual type used at a call site.
- Type inference
- The compiler deducing a type from context.
1. Understand the idea
Generics express shared structure without converting everything to strings or untyped values. A function can accept a slice of any T if it only needs operations that every slice supports. When it needs extra operations on T, it must declare appropriate bounds. Start with the smallest contract that the function really needs.
2. Save, run and observe
Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.
fn first<T>(items: &[T]) -> Option<&T> { items.first() }
fn main() {
println!("number={}", first(&[7, 8]).unwrap());
println!("word={}", first(&["Rust", "Python"]).unwrap());
}
What you should see · example output
number=7 word=Rust
rustc --edition=2024 lesson.rs -o lesson
./lesson3. Explain the result
The helper borrows either integer or string elements without copying them. Here unwrap is safe because each array literal is visibly nonempty; a user-supplied collection still needs a None branch. The returned reference is tied to the input slice, not to a new local value.
YOUR TURN
A small check before you continue
Does first need T to implement arithmetic?
Show a suggested answer
No. It uses the slice API and returns a reference. Adding an arithmetic bound would be unnecessary.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
