0Pricing
Learn Rust Coding · Lesson

Defining Traits

Shared behavior.

Defining Traits is a free Learn Rust Coding lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

Frequently asked questions

Is the “Defining Traits” lesson free?

Yes — the full text of “Defining Traits” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.

What will I learn in “Defining Traits”?

Shared behavior. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn Rust Coding?

No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Defining Traits” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn Rust Coding lesson?

Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Defining Traits
  2. Trait Objects and dyn
  3. Static vs Dynamic Dispatch
  4. Default Methods
← Back to Learn Rust Coding