Rust Fundamentals · 15 XP Pro

Tuple structs and newtypes

A tuple struct is a struct whose fields have no names, only positions. You read them with .0, .1, and so on:

pub struct Rgb(pub u8, pub u8, pub u8);

let red = Rgb(255, 0, 0);
println!("{}", red.0);

A tuple struct with a single field is called a newtype. It wraps an existing type to give it a distinct identity. Meters(f64) and Feet(f64) both hold an f64, but the compiler will not let you pass one where the other is expected. That catches unit mix-ups at compile time and costs nothing at runtime.

To get the inner value out, use .0. To make a new wrapped value, call the struct name like a function.

Your task

The tests construct these types and read .0, so they and their field must be pub.

  1. Define pub struct Meters(pub f64) and pub struct Feet(pub f64).
  2. Write pub fn to_feet(m: Meters) -> Feet using 1 m = 3.28084 ft.
  3. Write pub fn add_meters(a: Meters, b: Meters) -> Meters returning their sum.

Next lesson →

Sign in to run your code. It's free.