CodeBlanks Logo Icon CodeBlanks

What is a trait?

Define shared behavior with traits.

What is a trait?

A trait is a contract of behaviour that types can share: "every type implementing this has these methods". It's similar to interfaces in other languages:

trait Ses {
    fn ses(&self) -> String;
}

struct Kedi;

impl Ses for Kedi {
    fn ses(&self) -> String {
        String::from("Miyav")
    }
}

A trait only defines the signature; each type writes the body in its own impl Trait for Type block.

Calling a trait method

Trait methods are called with a dot like normal methods, but the trait must be in scope. If it's defined in the same module it already is; if it comes from another crate, bring it in with use:

use std::fmt::Write;   // to apply the write! macro to a String

let mut s = String::new();
write!(s, "{}-{}", 1, 2).unwrap();
println!("{s}");   // 1-2

If the trait isn't in scope, the compiler says "method not found ... items from traits can only be used if the trait is in scope" and suggests the missing use line.

Practice First trait

Define trait Ses with the method fn ses(&self) -> String. Implement it for struct Kedi; ("Miyav") and print the result of Kedi.ses().

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
trait Ses {
    fn ses(&self) -> String;
}

struct Kedi;

impl Ses for Kedi {
    fn ses(&self) -> String {
        String::from("Miyav")
    }
}

fn main() {
    println!("{}", Kedi.ses());
}

Expected output

Miyav

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if you forget to write the body of a trait method?

  • The method runs empty
  • Runtime panic
  • It warns
  • Compile error: missing trait item (E0046) Correct answer

Explanation: Every method without a default body must be written in the implementation.

2 Implement the trait

Question
impl Ses ____ Kedi {
    fn ses(&self) -> String {
        String::from("Miyav")
    }
}
Answer
impl Ses for Kedi {
    fn ses(&self) -> String {
        String::from("Miyav")
    }
}

Explanation: A trait implementation has the form impl Trait for Type.

3 Syntax and meaning

Term Meaning
trait Ses { .. } Contract definition
impl Ses for Kedi Implementation
fn ses(&self) -> String; Signature without body
use std::fmt::Write Brings the trait into scope

All lessons in Intermediate