Rust Generics
Describe one operation for a constrained family of types.
How it works
Generics parameterise a function or type over other types. A generic body can use only the operations supported by its bounds. This keeps an interface reusable without converting every value to an unstructured representation. Constraints should follow the operation’s actual needs; broad bounds can make callers do extra work or hide unnecessary copying.
Run the code
Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.
This complete example was executed in the stated local review environment.
Example
fn main() {
fn first<T>(items: &[T]) -> Option<&T> { items.first() }
assert_eq!(first(&[3,5,8]), Some(&3));
assert_eq!(first(&["north","south"]), Some(&"north"));
assert_eq!(first::<u32>(&[]), None);
println!("Generic borrowed lookup handles numbers, text and empty input");
}
Expected result
Generic borrowed lookup handles numbers, text and empty input
The helper only borrows an element, so it does not need a Clone or Copy bound. It works for different element types and preserves the empty-input case. The returned reference cannot outlive the input slice. A generic signature can state this relationship without duplicating the implementation for every record type.
Primary technical reference: Rust documentation.