結構體

與 C 和 C++ 一樣,Rust 支援自訂結構體:

struct Person {
    name: String,
    age: u8,
}

fn describe(person: &Person) {
    println!("{} is {} years old", person.name, person.age);
}

fn main() {
    let mut peter = Person { name: String::from("Peter"), age: 27 };
    describe(&peter);

    peter.age = 28;
    describe(&peter);

    let name = String::from("Avery");
    let age = 39;
    let avery = Person { name, age };
    describe(&avery);

    let jackie = Person { name: String::from("Jackie"), ..avery };
    describe(&jackie);
}
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.