Bitpath

Lesson 1 · Unit 05

Structs and methods

Named fields, impl, &self and &mut self, new

13 exercisesabout 3 min

What you practise

  • A struct, impl, &self and &mut self, associated functions like new, #[derive(Debug)]

Try a question from this lesson

Pick one

A shop keeps one item in a tuple: its name, how many it has, and the price in cents. What does this print?

Rust
let item = ("pen", 3, 250);
println!("{}", item.1 * item.2);
Hint

Positions in a tuple count from 0.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

A struct names its fields

A struct is a type you design yourself. You list its fields, each with a name and a type.

To make a value, write the struct's name and give every field a value. To read a field, write a dot and the field's name.

Struct names start with a capital letter, like String and Vec.

Rust
struct Item {
    name: String,
    count: i32,
    price: i32,
}
let pen = Item {
    name: String::from("pen"),
    count: 3,
    price: 250,
};
println!("{}", pen.count);

Concept

Methods live in impl

A function that belongs to a struct is called a method. Methods go in an impl block that carries the struct's name.

The first parameter is &self: a borrow of the value the method was called on. Inside the method, self.count is that value's field.

You call a method with a dot, as you did with push and len.

Rust
struct Item { count: i32, price: i32 }
impl Item {
    fn worth(&self) -> i32 {
        self.count * self.price
    }
}
let pen = Item { count: 3, price: 250 };
println!("{}", pen.worth());

Concept

A function that builds the value

A function in impl with no self belongs to the type, not to one value. You call it with ::, as in String::from and Vec::new.

The usual name for one that builds a fresh value is new. It keeps the starting rules in one place: here, every counter starts at 0.

Rust
struct Counter { n: i32 }
impl Counter {
    fn new() -> Counter {
        Counter { n: 0 }
    }
}
let c = Counter::new();
println!("{}", c.n);

9 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 2× fill the blanks
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy