Structs
Al igual que C y C++, Rust admite estructuras (struct) personalizadas:
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.
Puntos Clave:
- Las estructuras funcionan como en C o en C++.
- Al igual que en C++, y a diferencia de C, no se necesita typedef para definir un tipo.
- A diferencia de C++, no existe ninguna herencia entre las estructuras.
- 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. - La siguiente diapositiva presentará las estructuras de tuplas, que se utilizan cuando los nombres de los campos no son importantes.
- Zero-sized structs (e.g.
- 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.