Rust course Lesson 6 of 6

Rust from zero: a trait is a method list

A trait names the methods a function needs. Label asks for label. Item implements it. show prints latte $4.50.

Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.

Back to top

A trait is a list of methods. A struct implements the trait by writing those methods. A function can then take impl Label and call label without naming Item. A discount line with the same method can be passed in later, and the receipt printer stays.

A trait is the method you can call#

A trait names methods. impl Label for Item supplies label for that struct. show takes &impl Label, a shared borrow of some type that has the trait. The function can call label and cannot see cents, because cents is not part of the trait. The borrow ends when show returns, and the latte is still owned by main. Another type can implement Label and be passed to the same function.

show borrows something that has label
  1. Itemlabellatte $4.50
  2. no impllabeldoes not compile
struct Item {
    name: String,
    cents: i32,
}

trait Label {
    fn label(&self) -> String;
}

impl Label for Item {
    fn label(&self) -> String {
        format!("{} ${}.{:02}", self.name, self.cents / 100, self.cents % 100)
    }
}

fn show(item: &impl Label) {
    println!("{}", item.label());
}

fn main() {
    let latte = Item { name: String::from("latte"), cents: 450 };
    show(&latte);
}
latte $4.50

impl Label for Item is the opt-in#

The trait says label borrows self and returns a String. impl Label for Item provides that method. show accepts any reference whose type implements Label. main passes &latte. The print is latte $4.50.

The & on the argument matches &self on the method. show borrows the item. It does not take ownership, so the latte could be used again after the call. A trait method that needed to change the struct would say &mut self, and show would take &mut impl Label.

One method until you need a second#

show calls label and nothing else, so the trait has one method. Adding methods the caller does not use forces every implementor to write them. Start with the call you have. A second struct implements Label the same way, with its own fields, and show stays as it is.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.