Welcome to the Rust Type Parameters tutorial! Today, we'll delve into one of the most powerful features of Rust's type system, which allows us to write generic code that can work with a variety of data types.
Type parameters are placeholders for specific types that will be filled in when you use a generic function or struct. They enable Rust to create a single piece of code that can work with multiple data types, making our code more flexible and reusable.
fn greet<T>(value: T) {
println!("Hello, {}.", value);
}In the example above, T is a type parameter. The greet function accepts a value of any type T and prints a greeting.
Let's explore type parameters in more detail by creating a simple generic struct and function.
struct Pair<T> {
x: T,
y: T,
}In this example, we define a struct called Pair with a single type parameter T. The struct has two fields, x and y, both of type T.
let int_pair = Pair { x: 1, y: 2 };
let string_pair = Pair { x: "Hello", y: "World" };We can create instances of the Pair struct with different types, such as integers and strings, as shown above.
fn larger<T: std::cmp::PartialOrd + std::clone::Clone>(a: T, b: T) -> T {
if a > b {
a.clone()
} else {
b.clone()
}
}In this example, we define a generic function called larger that takes two arguments of the same type T. The function checks if a is larger than b, and returns either a or b (cloned to prevent data races). The function requires T to implement the std::cmp::PartialOrd trait for comparison and the std::clone::Clone trait for cloning.
let integer_result = larger(3, 2);
let string_result = larger("Apple", "Banana");In this example, we call the larger function with integers and strings, and it correctly returns the larger value in each case.
What is the purpose of type parameters in Rust?
That's all for today! By understanding type parameters, you've taken a big step towards mastering Rust's powerful type system. Keep exploring, keep coding, and remember to always ask for help when you need it! 💡💡💡