Struct & Impl — Rust

struct Order { customer: String, items: Vec<u32>, take_away: bool } makes a new type with fields (named values). A value is filled in with Order { ... }, and…

Sari's order has three things: her name, the price of each item, and a "take-away" tick. If you keep them in three separate variables, there are nine variables once Budi's and Rina's orders arrive, and they are easy to mix up. It's tidier to write the three on one order slip.

That's what a struct is for: a struct groups several related values into one new type of your own. Then impl (short for implementation) adds functions that belong to that type. The order slip at Rusdi's Pancake Stall is an example. Its layout is printed in advance: a box for the customer's name, a list of item prices, and a "take-away" tick box. Every customer gets one slip with their own details. The cashier also has fixed procedures for a slip: add an item, calculate the total, and close the slip when the customer pays. In code, the printed layout is the struct, one filled-in slip is one struct value, and the cashier's procedures are the functions inside the impl.

Defining a struct and filling it in

The code below writes the layout of the slip Order, then fills in one slip for Sari:

struct Order {
    customer: String,
    items: Vec<u32>,
    take_away: bool,
}

fn main() {
    let mut order = Order {
        customer: String::from("Sari"),
        items: vec![32, 32, 38],
        take_away: false,
    };
    order.take_away = true;
    println!("{} orders {} items", order.customer, order.items.len());
    println!("Take-away: {}", order.take_away);
}
Sari orders 3 items
Take-away: true

impl: methods and associated functions

Below, impl Order adds four functions that belong to Order: make a new slip, add an item, calculate the total, and close the slip.

struct Order {
    customer: String,
    items: Vec<u32>,
    take_away: bool,
}

impl Order {
    fn new(customer: String) -> Order {
        Order { customer, items: Vec::new(), take_away: false }
    }

    fn add(&mut self, price: u32) {
        self.items.push(price);
    }

    fn total(&self) -> u32 {
        self.items.iter().sum()
    }

    fn finish(self) -> String {
        let mode = if self.take_away { "take-away" } else { "eat in" };
        format!("{} pays {}, {}", self.customer, self.total(), mode)
    }
}

fn main() {
    let mut order = Order::new(String::from("Sari"));
    order.add(32);
    order.add(32);
    order.add(38);
    order.take_away = true;
    println!("Total: {}", order.total());
    println!("{}", order.finish());
}
Total: 102
Sari pays 102, take-away

&self, &mut self and self

The form of self decides what happens to the slip when the method is called:

First parameter Meaning Example After the call
&self borrows it to read total order can still be used
&mut self borrows it to change add can still be used; the variable must be let mut
self takes the slip (a move) finish order has moved and can't be used again

The method finish closes the slip, and its parameter is self. Now add one line to the main in the impl example above: after println!("{}", order.finish());, call order.total(). Before you look at the result, guess: does the code compile?

error[E0382]: borrow of moved value: `order`
  --> src/main.rs:34:20
   |
27 |     let mut order = Order::new(String::from("Sari"));
   |         --------- move occurs because `order` has type `Order`, which does not implement the `Copy` trait
...
33 |     println!("{}", order.finish());
   |                          -------- `order` moved due to this method call
34 |     println!("{}", order.total());
   |                    ^^^^^ value borrowed here after move
   |
note: `Order::finish` takes ownership of the receiver `self`, which moves `order`

It doesn't compile. finish(self) takes the slip, exactly like the String that moved into kitchen in the first lesson. So after order.finish(), order has moved and can't be used again. Use self only for a method that is really the last use of the value, like closing the slip. If you forget to write let mut, every call to add is refused with cannot borrow `order` as mutable, as it is not declared as mutable (E0596).

#[derive(Debug, Clone, PartialEq)] and {:#?}

At first, a struct of your own can't be printed with {:?}, copied with .clone() or compared with ==. These three abilities are traits: Debug, Clone and PartialEq. The line #[derive(...)] above the struct tells the compiler to write the code for those traits for your struct automatically. The code below uses all three:

#[derive(Debug, Clone, PartialEq)]
struct Order {
    customer: String,
    items: Vec<u32>,
    take_away: bool,
}

// impl Order { ... } the same as above

fn main() {
    let mut order = Order::new(String::from("Sari"));
    order.add(32);
    order.add(32);
    order.add(38);
    let copy = order.clone();
    println!("{}", order == copy);
    println!("{:?}", order);
    println!("{:#?}", order);
    println!("{}", order.finish());
}
true
Order { customer: "Sari", items: [32, 32, 38], take_away: false }
Order {
    customer: "Sari",
    items: [
        32,
        32,
        38,
    ],
    take_away: false,
}
Sari pays 102, eat in

Update syntax, tuple structs and unit structs

Suppose sari is Sari's slip. When you fill in a new slip, ..sari at the end fills every field you didn't write with the value from sari. But String and Vec fields are moved, not copied:

let budi = Order {
    customer: String::from("Budi"),
    take_away: true,
    ..sari
};
println!("{:?}", sari);

The last line is refused with borrow of partially moved value: `sari` (part of sari has moved). The reason is that sari.items (a Vec) has moved into budi. If sari is still needed, write ..sari.clone().

A tuple struct has fields without names, read by number: struct Dollars(u32);, then let total = Dollars(102); and total.0 gives 102. It is used to make a new type that can't be mixed up with a plain number. If the function is fn pay(amount: Dollars), the compiler refuses pay(5) with expected `Dollars`, found integer. A unit struct has no fields at all, struct Cashier;, and its value is written Cashier. A unit struct is useful for a type that doesn't need to hold any data but still needs methods, like struct Cat; in the exercise of the Traits lesson.

⚠️ Slips that can't be changed, printed, or used again

TL;DR: struct Order { customer: String, items: Vec<u32>, take_away: bool } makes a new type with fields (named values). A value is filled in with Order { ... }, and its fields are read with a dot, order.items. impl Order adds functions that belong to that type: an associated function without self is called Order::new(...), a method with self (the value written before the dot) is called order.total(). &self borrows that value to read it, and &mut self borrows it to change it (the variable is let mut). self takes the value, so the variable can't be used again. Field init shorthand writes customer once when the variable and the field have the same name. ..sari fills the remaining fields from another Order value, sari (and moves its String and Vec fields). A tuple struct Dollars(u32) has fields without names, read with .0, and a unit struct Cashier has no fields. #[derive(Debug, Clone, PartialEq)] tells the compiler to write three traits (abilities): {:?}/{:#?} to print, .clone() to copy, and == to compare.

⚡ One slip, several fields

Write:

struct Order {
    customer: String,
    items: Vec<u32>,
    take_away: bool,
}

Meaning: A struct groups several values into one new type, here Order (an order slip). Each field (a named value inside a struct) has a name and a type. One value is filled in with Order { ... }. If that value is kept in the variable order, its fields are read with a dot: order.customer.

⚡ Method or associated function

Write:

impl Order {
    fn new(customer: String) -> Order {
        Order { customer, items: Vec::new(), take_away: false }
    }

    fn total(&self) -> u32 {
        self.items.iter().sum()
    }
}

Meaning: impl Order adds functions that belong to Order. new has no self, so new is an associated function, called through the type's name: Order::new(...). total has self (the value written before the dot), so total is a method, called with a dot: order.total(). Inside new, customer is written once because the parameter and the field have the same name.

⚡ self takes the slip

Guess first: the method fn finish(self) closes the slip. After order.finish(), the code calls order.total(). Does the code compile?

No. self without & takes the slip, so order has moved. The compiler refuses with borrow of moved value: a value is used after it was moved.

Meaning: &self borrows the value to read it, and &mut self borrows it to change it (the variable must be let mut). self takes the value, so the variable can't be used again.

What you will learn