Welcome back to CodeYourCraft! Today, we're diving into one of Rust's powerful features: Generic Functions. Let's explore how to create flexible and reusable functions that work with various data types.
In Rust, generic functions allow you to define functions that work with multiple data types. This means you can write a function once, and it will automatically adapt to work with different types, without you having to write separate functions for each type.
Let's create a generic function that can calculate the sum of two values.
fn sum<T>(a: T, b: T) -> T {
a + b
}In this example, T is a type parameter. We use it to define the type that our function sum can work with. The sum function takes two arguments of the same type T, adds them, and returns the result of the same type T.
You can call this function with different types, like integers or floats:
let int_sum = sum(1, 2); // int_sum has type i32
let float_sum = sum(1.0, 2.0); // float_sum has type f64In Rust, you can define multiple type parameters in a function by separating them with commas. You can also define default types for the type parameters, which will be used if no specific type is provided when calling the function.
fn identity<T>(value: T) -> T {
value
}
// Calling the function with an i32
let x: i32 = 10;
let y = identity(x); // y has type i32
// Calling the function with a String
let s: String = "Hello".to_string();
let t = identity(s); // t has type StringIn this example, identity is a generic function that simply returns the provided value. We defined the type parameter T with no default type. This means you must specify a type when calling the function.
When working with generic functions and types, Rust introduces the concept of lifetimes to ensure type safety. Lifetimes help you to express relationships between references and their lifetimes. You don't need to worry about lifetimes too much as beginners, but understanding them will help you write more advanced generic code.
Happy coding! In the next lesson, we'll explore more about Rust's generic types and traits. 🚀