0Pricing
Learn Rust Coding · Leçon

Définition de traits

Comportement partagé

Définition de traits est une leçon Learn Rust Coding gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Learn Rust Coding, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Learn Rust Coding comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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:

  • trait declares shared behavior
  • impl Trait for Type provides the methods
  • Trait bounds (T: Trait, +, where) constrain generics
  • The orphan rule keeps implementations coherent

Questions Fréquemment Posées

La leçon « Définition de traits » est-elle gratuite ?

Oui — le texte complet de « Définition de traits » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Learn Rust Coding, passe à CoddyKit PRO. Le cours Learn Rust Coding comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Définition de traits » ?

Comportement partagé Tu pratiques Learn Rust Coding avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Learn Rust Coding ?

Aucune expérience préalable n'est requise. Learn Rust Coding sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.

Combien de temps prend la leçon « Définition de traits » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Learn Rust Coding ?

Oui. Chaque leçon Learn Rust Coding inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Définition de traits
  2. Objets de traits et dyn
  3. Dispatch statique ou dynamique
  4. Méthodes par défaut
← Retour à Learn Rust Coding