Introduction
Tuple structs let you group related values together without naming each field. They are simple and easy to use.
Tuple structs let you group related values together without naming each field. They are simple and easy to use.
struct Name(Type1, Type2, ...);
Color with three u8 values for red, green, and blue.struct Color(u8, u8, u8); let black = Color(0, 0, 0);
Point with two f64 values for x and y coordinates.struct Point(f64, f64); let origin = Point(0.0, 0.0);
struct Pair(i32, i32); let pair = Pair(10, 20); println!("First: {}, Second: {}", pair.0, pair.1);
This program defines a tuple struct Color and creates an instance for red color. It prints each color component by accessing fields by position.
struct Color(u8, u8, u8);
fn main() {
let red = Color(255, 0, 0);
println!("Red color values: R={}, G={}, B={}", red.0, red.1, red.2);
}Tuple structs are useful when you want to group data but don't need named fields.
You can implement methods on tuple structs just like regular structs.
Access fields by position starting at zero, like tuples.
Tuple structs group related values without naming each field.
Access fields by position using dot and index.
They add meaning to tuples by giving them a name.
Color with three u8 fields?struct Point(i32, i32);
fn main() {
let p = Point(10, 20);
println!("{}", p.1);
}
struct Size(u32, u32);
fn main() {
let s = Size { 100, 200 };
println!("{}", s.0);
}
struct Rectangle(u32, u32);, how can you write a function area that takes a Rectangle and returns its area (width * height)?Pass the test and this pattern moves unknown