Sintaxe Abreviada de Campos
Se você já tiver variáveis com os nomes corretos, poderá criar a estrutura (struct) usando uma abreviação:
#[derive(Debug)] struct Person { name: String, age: u8, } impl Person { fn new(name: String, age: u8) -> Person { Person { name, age } } } fn main() { let peter = Person::new(String::from("Pedro"), 27); println!("{peter:?}"); }
-
A função
newpoderia ser escrita utilizandoSelfcomo tipo, já que ele é intercambiável com o nome da struct#[derive(Debug)] struct Person { name: String, age: u8, } impl Person { fn new(name: String, age: u8) -> Self { Self { name, age } } } -
Implemente a trait
Default(Padrão) para a struct. Defina alguns campos e utilize valores padrão para os demais.#[derive(Debug)] struct Person { name: String, age: u8, } impl Default for Person { fn default() -> Person { Person { name: "Robô".to_string(), age: 0, } } } fn create_default() { let tmp = Person { ..Person::default() }; let tmp = Person { name: "Sam".to_string(), ..Person::default() }; } -
Métodos são definidos no bloco
impl. -
Use a sintaxe de atualização de estruturas para definir uma nova
structusandopeter. Note que a variávelpeternão será mais acessível após. -
Utilize
{:#?}para imprimir structs utilizando a representação de depuração (Debug).