Tuple Structs
If the field names are unimportant, you can use a tuple struct:
1. ```
struct Point(i32, i32);
```
3. ```
fn main() {
```
4. ```
let p = Point(17, 23);
```
5. ```
println!("({}, {})", p.0, p.1);
```
6. ```
}
```
This is often used for single-field wrappers (called newtypes):
1. ```
struct PoundsOfForce(f64);
```
2. ```
struct Newtons(f64);
```
4. ```
fn compute_thruster_force() -> PoundsOfForce {
```
5. ```
todo!("Ask a rocket scientist at NASA")
```
6. ```
}
```
8. ```
fn set_thruster_force(force: Newtons) {
```
9. ```
// ...
```
10. ```
}
```
12. ```
fn main() {
```
13. ```
let force = compute_thruster_force();
```
14. ```
set_thruster_force(force);
```
15. ```
}
```
This slide should take about 10 minutes.
- 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:
Newtonsin 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). - Demonstrate how to add a
f64value to aNewtonstype by accessing the single field in the newtype. - Rust generally doesn’t like inexplicit things, like automatic unwrapping or for instance using booleans as integers.
- Operator overloading is discussed on Day 3 (generics).
- The example is a subtle reference to the Mars Climate Orbiter failure.
