Rust tuple struct
Created By: chatGPT
Tuple structs in Rust are a way to create a new struct type that is defined by a tuple of elements, without necessarily giving names to those elements. This can be handy when you want to create a simple structure to group multiple values together. A tuple struct looks like a tuple but has a name. Here’s a quick overview of how to define and use a tuple struct.
struct Point(i32, i32);
fn main() {
let p = Point(10, 20);
println!("Point coordinates: ({}, {})", p.0, p.1);
}
In the code above, we define a tuple struct named Point that contains two elements: both are of type
i32
. In the main
function, we create a new instance of Point
and use the dot indexing notation to access its elements.struct Color(u8, u8, u8);
fn main() {
let c = Color(255, 0, 0);
println!("Color values: ({}, {}, {})", c.0, c.1, c.2);
}
You can define multiple tuple structs, each representing different logical groupings of values. Each instance can be created and accessed similarly, demonstrating the flexibility of using tuple structs for grouping.
struct Rectangle(u32, u32);
fn main() {
let rect = Rectangle(30, 50);
println!("Rectangle width: {}, height: {}", rect.0, rect.1);
}
Tuple structs are useful for types where the data is never intended to be accessed by name, keeping the code clearer and more concise. They can also implement traits, just like regular structs, which allows you to define behaviors for these data types.
impl Rectangle {
fn area(&self) -> u32 {
self.0 * self.1
}
}
fn main() {
let rect = Rectangle(30, 50);
println!("Area of rectangle: {}", rect.area());
}