typestar

Tuple and unit structs in Rust

Structs without field names: newtypes for meaning, unit structs for markers.

struct Meters(f64);
struct Rgb(u8, u8, u8);
struct Marker;

impl Meters {
    fn feet(&self) -> f64 {
        self.0 * 3.28084
    }
}

fn main() {
    let height = Meters(1.82);
    println!("{:.2} ft", height.feet());

    let accent = Rgb(124, 92, 255);
    println!("#{:02x}{:02x}{:02x}", accent.0, accent.1, accent.2);

    let _marker = Marker;
}

How it works

  1. A tuple struct's fields are reached by position: .0.
  2. A newtype wraps one value to give it a distinct type.
  3. A unit struct carries no data, only its identity.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
316
Tokens
101
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 3 of 4 in Compound values, step 9 of 39 in Language basics.

← Previous Next →