Product Types:
Product types represent a combination of multiple values. In Rust, product types are typically represented using structs or tuples. Here's an example using a struct:
struct Point {
x: i32,
y: i32,
}
let p = Point { x: 3, y: 4 };
In this example, Point is a product type that combines two i32 values, x and y, into a single structure. The p variable is an instance of the Point struct with x set to 3 and y set to 4.
Tuples are another way to represent product types in Rust:
let t: (i32, f64, bool) = (42, 3.14, true);
Here, t is a tuple that combines an i32, an f64, and a bool value into a single entity.
Sum Types:
Sum types, also known as tagged unions or enums, represent a value that can be one of several possible variants. In Rust, sum types are defined using the enum keyword. Here's an example:
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Triangle(f64, f64, f64),
}
let c = Shape::Circle(2.5);
let r = Shape::Rectangle(3.0, 4.0);
let t = Shape::Triangle(3.0, 4.0, 5.0);
In this example, Shape is a sum type that can be either a Circle with a radius, a Rectangle with a width and height, or a Triangle with three side lengths. The c, r, and t variables are instances of the Shape enum, each representing a different variant.
Sum types are useful when you need to represent a value that can have different forms or cases. Rust's match expression is commonly used to pattern match on the variants of a sum type:
fn area(shape: Shape) -> f64 {
match shape {
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Rectangle(w, h) => w * h,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
In this example, the area function takes a Shape value and uses a match expression to calculate the area based on the variant of the Shape.