Structs, enums e traits
Rust Traits
Describe shared behavior once and implement it for any type, like interfaces in other languages.
O que você vai aprender
- Defining a trait
- Default methods
- impl Trait and dyn Trait
trait Describe
DescribeDogkeeps the defaultRobotreplaces describe
Shared behavior for different types
A trait is a set of methods that a type can implement, similar to an interface in other languages. Code written against the trait works with every type that implements it.
Describe requires name and gives describe a default body. Dog keeps the default, while Robot replaces it. introduce accepts any type that implements Describe, and Box<dyn Describe> lets one vector hold values of different types.
Pontos-chave
- A trait lists methods a type must have.
- A default method can be kept or replaced.
- Box<dyn Trait> stores different types together.
Exemplo executável de Rust
main.rs
trait Describe {
fn name(&self) -> String;
fn describe(&self) -> String {
format!("This is {}.", self.name())
}
}
struct Dog;
struct Robot {
model: u32,
}
impl Describe for Dog {
fn name(&self) -> String {
String::from("a dog")
}
}
impl Describe for Robot {
fn name(&self) -> String {
format!("robot model {}", self.model)
}
fn describe(&self) -> String {
format!("Beep. I am {}.", self.name())
}
}
fn introduce(item: &impl Describe) {
println!("{}", item.describe());
}
fn main() {
introduce(&Dog);
introduce(&Robot { model: 7 });
let items: Vec<Box<dyn Describe>> = vec![Box::new(Dog), Box::new(Robot { model: 8 })];
println!("{} items", items.len());
}
This is a dog.
Beep. I am robot model 7.
2 itemsPratique
Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.
Terminou esta lição?
Marque como aprendida para acompanhar seu progresso.
Seu progresso está salvo neste navegador Entre para mantê-lo em todos os dispositivos.
Pratique com um desafio
Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.
Todos os desafios