9.4 Tuple Structs

Tuple structs are a hybrid between structs and tuples. They have a name but their fields are unnamed.

9.4.1 Defining Tuple Structs

struct StructName(Type1, Type2, /* ... */);

Example:

#![allow(unused)]
fn main() {
struct Color(u8, u8, u8);
}

9.4.2 Instantiating Tuple Structs

let red = Color(255, 0, 0);

9.4.3 Accessing Fields

Fields in tuple structs are accessed using dot notation with indices.

println!("Red component: {}", red.0);

9.4.4 Use Cases for Tuple Structs

  • Distinct Types: Tuple structs create new types, even if their fields have the same types as other tuple structs.

    #![allow(unused)]
    fn main() {
    struct Inches(i32);
    struct Centimeters(i32);
    let length_in = Inches(10);
    let length_cm = Centimeters(25);
    // Inches and Centimeters are different types, even though both contain an i32.
    }
  • This helps with type safety, preventing errors caused by mixing different units or concepts.

9.4.5 Comparison with Tuples

  • Regular tuples with the same types are considered the same type.

    #![allow(unused)]
    fn main() {
    let point1 = (1, 2);
    let point2 = (3, 4);
    // point1 and point2 are of the same type: (i32, i32)
    }
  • Tuple structs, even with the same fields, are different types.

9.4.6 Comparison with C

C does not have a direct equivalent of tuple structs. The closest comparison is using structs with anonymous fields, though this is not commonly used.