In Rust, you can define a generic function or struct by specifying a type parameter with angle brackets ‘<>‘. This allows you to write code that can adapt to work with different types of data, without having to write separate functions or structs for each type.
Here is an example of how to define a generic function that swaps the values of two variables using a type parameter:
fn swap<T>(a: &mut T, b: &mut T) {
let temp = *a;
*a = *b;
*b = temp;
}
In this function, ‘T‘ is the type parameter that specifies the type of the variables being swapped. The function takes two mutable references to values of type ‘T‘, swaps their values, and returns nothing.
Here is an example of how to use this function with two ‘i32‘ values:
fn main() {
let mut x = 42;
let mut y = 24;
println!("Before: x = {}, y = {}", x, y);
swap(&mut x, &mut y);
println!("After: x = {}, y = {}", x, y);
}
The output of this program will be:
Before: x = 42, y = 24
After: x = 24, y = 42
You can also define generic structs using type parameters. Here is an example of a ‘Point<T>‘ struct that can store values of any type:
struct Point<T> {
x: T,
y: T,
}
Here, ‘T‘ is the type parameter that specifies the type of the ‘x‘ and ‘y‘ values stored in the ‘Point‘. This allows you to create ‘Point‘ values with different types:
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3.14, y: 2.718 };
let p3 = Point { x: "hello", y: "world" };
}
In this example, ‘p1‘ is a ‘Point<i32>‘, ‘p2‘ is a ‘Point<f64>‘, and ‘p3‘ is a ‘Point<&str>‘.