// DOCS NAVIGATION
Traits_
SOURCE: content/docs/reference/03-tipos-compostos.md — 03 Tipos Compostos / 7. Traits
Declaração / Declaration
PT-BR:
Traits definem contratos de comportamento que tipos podem implementar. Um trait declara assinaturas de métodos e pode fornecer implementações padrão.
EN-US:
Traits define behavioral contracts that types can implement. A trait declares method signatures and can provide default implementations.
module traits
// Trait simples / Simple trait
trait Exibivel {
func exibir(&self) returns string
}
// Trait com implementação padrão / Trait with default implementation
trait Saudavel {
func saudar(&self) returns string
func saudar_alto(&self) returns string {
// Implementação padrão usa o método abstrato / Default impl uses abstract method
let s = self.saudar()
return f"OLÁ! {s}"
}
}
// Herança de trait / Trait inheritance
trait Animado: Exibivel {
func mover(&self) returns string
// Também precisa implementar Exibivel / Also needs to implement Exibivel
}
Implementação de Traits / Trait Implementation
record Pessoa {
nome: string,
idade: int
}
// Implementação do trait / Trait implementation
impl Exibivel for Pessoa {
func exibir(&self) returns string {
f"{self.nome} (idade: {self.idade})"
}
}
impl Saudavel for Pessoa {
func saudar(&self) returns string {
f"Olá, eu sou {self.nome}!"
}
// saudar_alto() já tem implementação padrão — não precisa repetir
// saudar_alto() has default implementation — no need to repeat
}
public func main() {
let p = Pessoa { nome: "Alice", idade: 30 }
let repr = p.exibir()
// "Alice (idade: 30)"
let s1 = p.saudar()
// "Olá, eu sou Alice!"
let s2 = p.saudar_alto()
// "OLÁ! Olá, eu sou Alice!"
}
Traits como Bounds em Genéricos / Traits as Generic Bounds
// Parâmetro genérico T deve implementar Exibivel / Generic T must implement Exibivel
func imprimir_todos<T: Exibivel>(items: [T], n: int) {
for i in 0..n {
println(items[i].exibir())
}
}
// Múltiplos bounds / Multiple bounds
func processar<T: Exibivel + Saudavel>(item: T) returns string {
return f"{item.saudar()} — {item.exibir()}"
}