Lesson 1 · Unit 05
Structs and methods
Named fields, impl, &self and &mut self, new
What you practise
- A struct,
impl,&selfand&mut self, associated functions likenew,#[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?
let item = ("pen", 3, 250);
println!("{}", item.1 * item.2);Hint
Positions in a tuple count from 0.
Correct answer
750
Why
item.1 is the count and item.2 is the price, so this is 3 times 250. It works, but .1 and .2 say nothing about what they hold. A struct lets you give each piece a name.
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.
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.
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.
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.