元组结构体

如果字段名称不重要,您可以使用元组结构体:

1. struct Point(i32, i32);

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

这通常用于单字段封装容器(称为 newtype):

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.

  • 如需对基元类型中的值的额外信息进行编码,使用 newtype 是一种非常好的方式,例如:
  • 数字会以某些单位来衡量:上方示例中为 Newtons。
  • The value passed some validation when it was created, so you no longer have to validate it again at every use: PhoneNumber(String) or OddNumber(u32).
  • 展示如何通过访问 newtype 中的单个字段,将 f64 值添加到 Newtons 类型。
  • Rust 通常不喜欢不明确的内容,例如自动解封或将布尔值用作整数。
  • 运算符过载在第 3 天(泛型)讨论。
  • 此示例巧妙地引用了火星气候探测者号 的失败事故。