Tuple struct
- Rust course
- Beginner
- Lesson 67/115
- 4 min
Learn the tuple struct type and when to use it.
Tuple structs
When field names are unnecessary, a tuple struct is used; fields are accessed with .0 and .1:
struct Renk(u8, u8, u8);
struct Nokta3(i32, i32, i32);
let turuncu = Renk(255, 128, 0);
println!("{}", turuncu.0); // 255Even though Renk and Nokta3 have the same shape, they are different types; one can't be passed where the other is expected.
Newtype and destructuring
A single-field tuple struct is called a newtype. Its value can be unpacked with a pattern:
struct Metre(f64);
struct Saniye(f64);
fn hiz(m: Metre, s: Saniye) -> f64 {
let Metre(yol) = m;
yol / s.0
}
println!("{}", hiz(Metre(100.0), Saniye(8.0))); // 12.5Writing hiz(Saniye(8.0), Metre(100.0)) is a compile error; the mix-up in order is caught.
Practice Colour code
Define struct Renk(u8, u8, u8); and create Renk(255, 128, 0). Print the fields side by side with the {:02X} format to produce #FF8000.
Starter code
fn main() {
// buraya yaz
}Sample solution
struct Renk(u8, u8, u8);
fn main() {
let k = Renk(255, 128, 0);
println!("#{:02X}{:02X}{:02X}", k.0, k.1, k.2);
}Expected output
#FF8000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the "newtype" pattern for?
- Provides inheritance
- Separates meaning over the same base type: Metre(f64) and Saniye(f64) can't be mixed up Correct answer
- Speeds up the program
- Allocates memory
Explanation: A single-field tuple struct adds type safety with no runtime cost.
2 Field access
struct Renk(u8, u8, u8);
let k = Renk(10, 20, 30);
let yesil = k.____; // 20
struct Renk(u8, u8, u8);
let k = Renk(10, 20, 30);
let yesil = k.1; // 20
Explanation: Tuple struct fields are numbered from 0; the second field is .1.
3 Definition and kind
| Term | Meaning |
|---|---|
struct Renk(u8, u8, u8); |
Tuple struct |
struct Metre(f64); |
Newtype |
struct Oyuncu { ad: String } |
Named-field struct |
let Metre(yol) = m; |
Unpacking with a pattern |