Structs

Like C and C++, Rust has support for custom structs:

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

Key Points:

  • Structs work like in C or C++.
    • Like in C++, and unlike in C, no typedef is needed to define a type.
    • Unlike in C++, there is no inheritance between structs.
  • Methods are defined in an impl block, which we will see in following slides.
  • 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.
    • The next slide will introduce Tuple structs, used when the field names are not important.
  • The syntax ..peter 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.