Named Structs
Like C and C++, Rust has support for custom structs:
1. ```
struct Person {
```
2. ```
name: String,
```
3. ```
age: u8,
```
4. ```
}
```
6. ```
fn describe(person: &Person) {
```
7. ```
println!("{} is {} years old", person.name, person.age);
```
8. ```
}
```
10. ```
fn main() {
```
11. ```
let mut peter = Person { name: String::from("Peter"), age: 27 };
```
12. ```
describe(&peter);
```
14. ```
peter.age = 28;
```
15. ```
describe(&peter);
```
17. ```
let name = String::from("Avery");
```
18. ```
let age = 39;
```
19. ```
let avery = Person { name, age };
```
20. ```
describe(&avery);
```
22. ```
let jackie = Person { name: String::from("Jackie"), ..avery };
```
23. ```
describe(&jackie);
```
24. ```
}
```
This slide should take about 10 minutes.
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.
- 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.
- If you already have variables with the right names, then you can create the struct using a shorthand.
- The syntax
..averyallows 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.
