Discover the Joy of Flexibility in Rust: Play Around with Generics in Structs and Enums!
Tired of writing repetitive code for different data types in Rust? Generics are here to save the day!
Generics are pretty awesome. They let you whip up functions, structs, methods, and enums that can juggle a whole range of data types – all without having to redo or rewrite the core logic. So, you get to keep your code neat, to the point, and ready for anything. Cool, right? 🦀
Let’s dive into some examples:
1. Generic Struct:
Imagine a Point
struct that can hold coordinates of any type, not just integers.
Rust
struct Point<T> {
x: T,
y: T,
}
or we can use with multiple generics that holds different data types
struct Point<T, U> {
x: T,
y: U,
}
Now, you can create Point
s with different data types:
Rust
let int_point = Point { x: 3, y: 5 };
let float_point = Point { x: 3.14, y: 2.7 };
let int_and_float = Point {x : 3, y: 3.4};
2. Generic Enum:
Create a result enum (Result
) that can hold either a successful value (Ok
) or an error (Err
), both with generic types! ✅️ ❌️
Rust
enum Result<T, E> {
Ok(T),
Err(E),
}
This Result
can be used for various operations:
Rust
let division_result = match divide(10, 0) {
Result::Ok(value) => value,
Result::Err(error) => handle_error(error),
};
Main Code Example:
Rust
fn main() {
let point = Point { x: 10, y: 20 };
println!("Point coordinates: ({}, {})", point.x, point.y);
let division_result = divide(10, 2);
match division_result {
Result::Ok(value) => println!("Division result: {}", value),
Result::Err(error) => println!("Error: {}", error),
}
}
fn divide<T>(x: T, y: T) -> Result<T, String>
where T: std::ops::Div<Output = T> {
// Implement division logic here
match y {
0 => Result::Err("Division by zero ".to_string()),
_ => Result::Ok(x / y),
}
}
// Implement error handling for divide function (not shown for brevity)
fn handle_error(error: String) {
println!("Error encountered: {error}");
}
This is just a taste of the power of generics in Rust. With them, you can write cleaner, more reusable code that adapts to different data types!
3. Generic Function:
In Rust, you can also use generics to create functions that can handle different data types. Check out this function that can swap the values of two pairs:
Rust
fn swap<T, U>(pair: (T, U)) -> (U, T) {
let (x, y) = pair;
(y, x)
}
Now, you can swap values of different types:
Rust
let result = swap((123, 456.789));
println!("Swapped pair: {:?}", result);
What’s your favorite way to use generics in Rust? Let us know in the comments!
LinkedIn: https://www.linkedin.com/in/himanshu-verma-2150b5252
GIPHY App Key not set. Please check settings