Rust variant
Created By: chatGPT
Rust Variants are a feature of the Rust programming language that allow you to define a type that can be one of several different types. This is particularly useful when dealing with data that can have multiple configurations or types. Variants are defined using the
enum
keyword, making it easy to create flexible and type-safe applications.enum Shape {
Circle(f64), // holds the radius
Rectangle(f64, f64), // holds width and height
Triangle(f64, f64, f64), // holds side lengths
}
In the example above, we define an
enum
called Shape
which can represent a Circle, a Rectangle, or a Triangle. Each variant can store different types and amounts of data. This enables you to maintain strong typing while also allowing for flexible design.fn area(shape: Shape) -> f64 {
match shape {
Shape::Circle(radius) => std::f64::consts::PI * radius * radius,
Shape::Rectangle(width, height) => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
The
area
function demonstrates how to use pattern matching with Rust variants. It takes a Shape
and calculates the area based on which variant it is using. This function effectively decouples the logic for different shapes while maintaining the integrity of the application's type system.fn main() {
let my_circle = Shape::Circle(2.0);
let my_rectangle = Shape::Rectangle(3.0, 4.0);
let my_triangle = Shape::Triangle(3.0, 4.0, 5.0);
println!("Area of circle: {}", area(my_circle));
println!("Area of rectangle: {}", area(my_rectangle));
println!("Area of triangle: {}", area(my_triangle));
}
In the
main
function, we create instances of each shape and compute their areas. Pattern matching provides a clean and efficient way to handle different types without sacrificing the safety and performance that Rust is known for. This is one of the many powerful features that makes Rust suitable for systems programming and application development.// Sample output when run:
// Area of circle: 12.566370614359172
// Area of rectangle: 12
// Area of triangle: 6