Introduction
Generics let us write code that works with many types without repeating it. This saves time and keeps code clean.
Generics let us write code that works with many types without repeating it. This saves time and keeps code clean.
fn function_name<T>(param: T) {
// code using param
}
struct StructName<T> {
field: T,
}The <T> means a generic type named T. You can use any name, but T is common.
Generics work with functions, structs, enums, and traits in Rust.
fn print_value<T: std::fmt::Display>(value: T) {
println!("Value: {}", value);
}struct Point<T> {
x: T,
y: T,
}let int_point = Point { x: 5, y: 10 };
let float_point = Point { x: 1.0, y: 4.0 };This program shows how one function can print different types using generics.
fn print_item<T: std::fmt::Display>(item: T) {
println!("Item: {}", item);
}
fn main() {
print_item(42);
print_item("hello");
}Generics help avoid repeating code for each type.
Rust checks types at compile time to keep code safe.
You can add rules (called traits) to generics to require certain abilities.
Generics let you write flexible, reusable code.
They work by using placeholders for types.
Rust ensures your generic code is safe and clear.
fn print_value<T>(value: T) {}print_value<T> uses a placeholder T to accept any type, showing flexibility.<T> after the function name to declare type parameters.fn example<T>(value: T) {}. Others miss brackets or have wrong parameter syntax.fn print_type(value: T) {
println!("Value: {}", value);
}
fn main() {
print_type(10);
print_type("hello");
}T requires the Display trait to print values with {}.print_type(10) prints "Value: 10" and print_type("hello") prints "Value: hello" because both implement Display.fn add<T>(a: T, b: T) -> T {
a + b
}
fn main() {
println!("{}", add(5, 10));
}+ operator requires the type T to implement the Add trait.T: std::ops::Add<Output = T> bound, causing a compile error.>, the type T must implement PartialOrd.T: PartialOrd. fn largest<T>(a: T, b: T) -> T { if a > b { a } else { b } } misses trait bound, C uses Copy which is unrelated to comparison, D uses Display which is for printing.Pass the test and this pattern moves unknown