Definição de traits
Comportamento compartilhado
Definição de traits é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
What Is a Trait?
A trait defines shared behavior — a set of methods a type can implement. It is similar to an interface in other languages.
Traits let different types agree on a common contract.
Declaring a Trait
Use the trait keyword followed by method signatures. The signatures declare what implementors must provide.
trait Greet {
fn hello(&self) -> String;
}
fn main() {
println!("trait declared");
}Implementing a Trait
Use impl TraitName for Type to provide the methods. The signature must match the trait exactly.
trait Greet {
fn hello(&self) -> String;
}
struct Dog;
impl Greet for Dog {
fn hello(&self) -> String {
String::from("Woof")
}
}
fn main() {
let d = Dog;
println!("{}", d.hello());
}Many Types, One Trait
Multiple types can implement the same trait, each in its own way. This is how traits unify behavior across unrelated types.
trait Greet { fn hello(&self) -> String; }
struct Dog;
struct Cat;
impl Greet for Dog { fn hello(&self) -> String { String::from("Woof") } }
impl Greet for Cat { fn hello(&self) -> String { String::from("Meow") } }
fn main() {
println!("{}", Dog.hello());
println!("{}", Cat.hello());
}Traits as Function Parameters
The impl Trait syntax accepts any type implementing the trait. The function works uniformly without knowing the concrete type.
trait Greet { fn hello(&self) -> String; }
struct Dog;
impl Greet for Dog { fn hello(&self) -> String { String::from("Woof") } }
fn announce(g: &impl Greet) {
println!("It says: {}", g.hello());
}
fn main() {
announce(&Dog);
}Trait Bounds on Generics
You can require that a generic type implements a trait using a trait bound. This unlocks the trait's methods inside the function.
trait Greet { fn hello(&self) -> String; }
struct Cat;
impl Greet for Cat { fn hello(&self) -> String { String::from("Meow") } }
fn shout<T: Greet>(g: &T) {
println!("{}!", g.hello().to_uppercase());
}
fn main() {
shout(&Cat);
}Multiple Bounds With +
Require several traits at once with +. Here a value must implement both a custom trait and the standard Clone.
trait Named { fn name(&self) -> String; }
#[derive(Clone)]
struct Item { label: String }
impl Named for Item {
fn name(&self) -> String { self.label.clone() }
}
fn describe<T: Named + Clone>(t: &T) {
let copy = t.clone();
println!("named {}", copy.name());
}
fn main() {
describe(&Item { label: String::from("box") });
}The where Clause
For many bounds, a where clause keeps the signature readable by moving the constraints below it.
use std::fmt::Debug;
fn print_all<T>(items: &[T])
where
T: Debug,
{
for it in items {
println!("{:?}", it);
}
}
fn main() {
print_all(&[1, 2, 3]);
}Traits Can Have Several Methods
A trait may declare many methods. Implementors must supply all required ones, giving the type a complete behavior set.
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String;
}
struct Square { side: f64 }
impl Shape for Square {
fn area(&self) -> f64 { self.side * self.side }
fn name(&self) -> String { String::from("square") }
}
fn main() {
let s = Square { side: 3.0 };
println!("{} area {}", s.name(), s.area());
}Why Traits Matter
Traits enable polymorphism without inheritance. They power generics, operator overloading (Add), formatting (Display), and much of the standard library.
They are the heart of Rust's abstraction model.
Coherence Rule
The orphan rule says you can implement a trait for a type only if you own the trait or the type. This prevents conflicting implementations across crates.
Quick Check
Test your understanding of traits.
Recap
You learned to define and use traits:
traitdeclares shared behaviorimpl Trait for Typeprovides the methods- Trait bounds (
T: Trait,+,where) constrain generics - The orphan rule keeps implementations coherent
Perguntas Frequentes
A aula “Definição de traits” é grátis?
Sim — o texto completo de “Definição de traits” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 4 aulas no total.
O que vou aprender em “Definição de traits”?
Comportamento compartilhado Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Learn Rust Coding?
Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “Definição de traits”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Learn Rust Coding?
Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Definição de traits
- Objetos de trait e dyn
- Despacho estático versus dinâmico
- Métodos padrão