src/user-defined-types/named-structs.md
Like C and C++, Rust has support for custom structs:
<!-- dprint-ignore-start --># // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
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);
}
Key Points:
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.Default trait which we will cover later.You can also demonstrate the struct update syntax here:
# // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
let jackie = Person { name: String::from("Jackie"), ..avery };
It 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.
It is mainly used in combination with the Default trait. We will talk about
struct update syntax in more detail on the slide on the Default trait, so we
don't need to talk about it here unless students ask about it.