Rust — Generics
Generic struct
struct Point<T> {
x: T,
y: T,
}
fn main() {
let int_point = Point { x: 5, y: 10 };
let float_point = Point { x: 1.0, y: 4.0 };
println!("Int: ({}, {})", int_point.x, int_point.y);
println!("Float: ({}, {})", float_point.x, float_point.y);
}
Multiple type parameters
struct Pair<A, B> {
first: A,
second: B,
}
fn main() {
let p = Pair { first: 1, second: "hello" };
println!("{}: {}", p.first, p.second);
}
Generic function
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in &list[1..] {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
let nums = vec![34, 50, 25, 100, 65];
println!("Largest: {}", largest(&nums));
}
Generic methods
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn x(&self) -> &T {
&self.x
}
}
impl Point<f64> {
fn distance_from_origin(&self) -> f64 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
Where clauses
use std::fmt::{Debug, Display};
fn compare<T: Display + PartialOrd>(a: T, b: T) -> bool {
a > b
}
fn main() {
println!("{}", compare(10, 5));
println!("{}", compare("hello", "world"));
}
Turbofish syntax
fn main() {
let nums: Vec<i32> = vec![1, 2, 3];
let nums2 = Vec::<i32>::from([1, 2, 3]);
let nums3 = (1..=3).collect::<Vec<i32>>();
println!("{:?}", nums);
}
Mini Practice
Write Rust code that:
- Creates a generic struct
- Writes a generic function with trait bounds
- Implements methods for a specific type
- Uses
whereclause
Up Next
In the next lesson, you'll learn about Lifetimes — references and borrowing in depth.
Related Topics
Frequently Asked Questions about Generics
What is Generics in Rust?
Generics is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Generics?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Generics.
Why is Generics important in Rust?
Generics is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.