Concept Flow - Tuple structs
Define tuple struct
Create instance with values
Access fields by position
Use instance in code
End
Tuple structs are like named tuples with types, defined once, then created with values and accessed by position.
struct Color(u8, u8, u8);
fn main() {
let black = Color(0, 0, 0);
println!("Black RGB: {}, {}, {}", black.0, black.1, black.2);
}| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define tuple struct Color(u8, u8, u8) | Creates a new type Color with 3 u8 fields | Type Color ready |
| 2 | Create instance black = Color(0, 0, 0) | Calls constructor with values 0,0,0 | black is Color(0,0,0) |
| 3 | Access black.0 | Get first field of black | 0 |
| 4 | Access black.1 | Get second field of black | 0 |
| 5 | Access black.2 | Get third field of black | 0 |
| 6 | Print values | Prints 'Black RGB: 0, 0, 0' | Output: Black RGB: 0, 0, 0 |
| Variable | Start | After Step 2 | Final |
|---|---|---|---|
| black | undefined | Color(0, 0, 0) | Color(0, 0, 0) |
Tuple structs define a named type with unnamed fields. Syntax: struct Name(Type1, Type2, ...); Create instance: let x = Name(val1, val2); Access fields by position: x.0, x.1, ... Useful for simple grouped data with type safety.
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