Definición de traits
Comportamiento compartido
Definición de traits es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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
Preguntas frecuentes
¿La lección «Definición de traits» es gratis?
Sí — el texto completo de «Definición de traits» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 4 lecciones en total.
¿Qué aprenderé en «Definición de traits»?
Comportamiento compartido Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Learn Rust Coding?
No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «Definición de traits»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?
Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Definición de traits
- Objetos trait y dyn
- Despacho estático frente a dinámico
- Métodos predeterminados