Structs
Um struct agrupa valores relacionados sob um tipo nomeado. Diferente de uma tupla, todo campo tem um nome, o que torna o código que o cria e usa autoexplicativo.
struct Person {
name: String,
age: u32,
}
fn main() {
let alice = Person {
name: String::from("Alice"),
age: 30,
};
println!("{} is {} years old", alice.name, alice.age);
}Alice is 30 years old
Métodos com impl
Um bloco impl anexa funções a um struct. Um método que recebe &self toma emprestada a instância sobre a qual é chamado, lendo seus campos sem tomar seu ownership — rect.area() abaixo lê width e height sem consumir rect.
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 10, height: 5 };
println!("Area: {}", rect.area());
}Area: 50
Próximo: enums e pattern matching — representar um valor que é uma entre várias variantes distintas, e a garantia do match de que você tratou cada uma delas.
Practice Exercise
Defina um struct Book com os campos title: String e price: f64. Adicione um método total(&self, quantity: u32) -> f64 que retorne self.price * quantity as f64. Crie um Book com title "Dune" e price 15.0, depois imprima book.total(3).