结构体

与 C 和 C++ 一样,Rust 支持自定义结构体:

  1. struct Person {
  2. name: String,
  3. age: u8,
  4. }
  5. fn describe(person: &Person) {
  6. println!("{} is {} years old", person.name, person.age);
  7. }
  8. fn main() {
  9. let mut peter = Person { name: String::from("Peter"), age: 27 };
  10. describe(&peter);
  11. peter.age = 28;
  12. describe(&peter);
  13. let name = String::from("Avery");
  14. let age = 39;
  15. let avery = Person { name, age };
  16. describe(&avery);
  17. let jackie = Person { name: String::from("Jackie"), ..avery };
  18. describe(&jackie);
  19. }

This slide should take about 10 minutes.

关键点:

  • 结构体的运作方式与使用 C 或 C++ 时类似。
    • 不需要 typedef 即可定义类型,这与使用 C++ 类似,但与使用 C 不同。
    • 与使用 C++ 不同的是,结构体之间没有继承关系。
  • This may be a good time to let people know there are different types of structs.
    • Zero-sized structs (e.g. struct Foo;) might be used when implementing a trait on some type but don’t have any data that you want to store in the value itself.
    • 下一张幻灯片将介绍元组结构体,当字段名称不重要时使用。
  • If you already have variables with the right names, then you can create the struct using a shorthand.
  • The syntax ..avery allows us to copy the majority of the fields from the old struct without having to explicitly type it all out. It must always be the last element.