Rust course Lesson 2 of 6

Rust from zero: a struct is the object

A struct groups fields, and impl adds a method. Item holds a drink and a price in cents. label 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 struct is the object. The fields are the data. impl is where the methods go. label borrows the struct, reads the fields, and returns a String you can print on a cup.

The struct owns its fields#

Item owns a String and an i32. String::from("latte") allocates the text so the struct can hold it after the statement ends. A &str would have to borrow from somewhere that outlives the struct. label takes &self, a shared borrow, so it can read the fields and return a new String without taking ownership of the drink. After the call, the item is still there. The returned string is a separate allocation. Cents stay a whole number so the price never becomes a binary fraction.

One drink, two fields, one label
  1. nameStringlatte
  2. centsi32450
  3. labelStringlatte $4.50
struct Item {
    name: String,
    cents: i32,
}

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

fn main() {
    let latte = Item {
        name: String::from("latte"),
        cents: 450,
    };
    println!("{}", latte.label());
}
latte $4.50

&self is the borrow#

Item owns a String and an i32. String::from("latte") makes an owned string, because the field must own its text. The "latte" in quotes is a &str, and String::from copies those bytes into a String.

fn label(&self) borrows the item for the call. latte.label() does not move latte. You can call label again. format! builds an owned String, and println! prints it. self.name and self.cents are the fields of the borrowed item. Dividing by 100 happens only in that format, when a person reads the price.

Cents are an i32 on purpose#

450 is a count of cents, which is $4.50. An i32 holds it exactly. A floating type would make you explain rounding on every add. The struct keeps the int. label is the receipt. The next lesson is the tip about who is allowed to use a String after you assign it.

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.