1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-27 11:08:45 +02:00
Files
comprehensive-rust/src/structs/tuple-structs.md
Igor Petruk c109dabf5f Update tuple-structs.md (#226)
* Update tuple-structs.md

I am adding more information about newtypes. The speaker can get questions about it or may wish to encourage this great pattern.

* Fix typos and explanation

Co-authored-by: Andrew Walbran <qwandor@google.com>
2023-01-23 11:38:37 +00:00

956 B

Tuple Structs

If the field names are unimportant, you can use a tuple struct:

struct Point(i32, i32);

fn main() {
    let p = Point(17, 23);
    println!("({}, {})", p.0, p.1);
}

This is often used for single-field wrappers (called newtypes):

struct PoundOfForce(f64);
struct Newtons(f64);

fn compute_thruster_force() -> PoundOfForce {
    todo!("Ask a rocket scientist at NASA")
}

fn set_thruster_force(force: Newtons) {
    // ...
}

fn main() {
    let force = compute_thruster_force();
    set_thruster_force(force);
}

Newtypes are a great way to encode additional information about the value in a primitive type, for example:

  • The number is measured in some units: Newtons in the example above.
  • The value passed some validation when it was created, so you no longer have to validate it again at every use: 'PhoneNumber(String)orOddNumber(u32)`.