🎓 A1Learner
🔍

Rust Marker Traits

A marker trait is a trait with no methods at all. The trait works as a label on a type.

An empty trait is a label

Use a trait with an empty body as a label. It promises no behaviour — the name itself is the whole meaning. A type gets the label with an impl line:

trait Public {}
struct Poster;
impl Public for Poster {}

The label works as a bound

Use the label as a bound: share accepts only types that carry the label:

fn share<T: Public>(_item: &T) -> &str { "shared" }
let poster = Poster;
println!("{}", share(&poster));

No label, no entry

Diary never received the label, so this call is refused at compile time with error E0277. The refusal is the feature:

let diary = Diary;
share(&diary);

Example

trait Public {}
struct Poster;
struct Notice;
struct Diary;
impl Public for Poster {}
impl Public for Notice {}
fn share<T: Public>(_item: &T) -> &str { "shared" }
fn main() {
    let poster = Poster;
    let notice = Notice;
    let _diary = Diary;
    println!("poster: {}", share(&poster));
    println!("notice: {}", share(&notice));
}

Key points

  • A marker bound unlocks no methods.
  • There are none to call.
  • Its whole job is to allow or refuse code.
  • Standard-library labels came earlier.
  • Eq adds no methods of its own.
  • Send and Sync are pure labels.
  • The compiler checks them.
  • Use a marker trait when the fact itself matters.
  • This type is safe to share.
  • It is safe to copy.
  • It is ready to publish.
  • And no method could express that fact.
  • It stores no data and costs nothing when the program runs.
  • A marker trait labels a type with its name alone.

In this example, Public is an empty trait: it names a label and nothing more. Poster and Notice receive the label with an impl line each. Diary does not. The share function demands the label as a bound. So share works on the poster and on the notice. Both lines print shared. Calling share on the diary would fail at compile time with E0277. Diary never received the label. The refusal is the feature.

Note

A marker trait is checked only at compile time.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does an empty marker trait give a type?