impl block
- Rust course
- Beginner
- Lesson 71/115
- 4 min
Define methods on a struct with impl.
The impl block
Methods are attached to a type inside an impl block. The first parameter is self and represents the instance the method is called on:
struct Kutu { en: u32, boy: u32 }
impl Kutu {
fn alan(&self) -> u32 {
self.en * self.boy
}
}
let k = Kutu { en: 3, boy: 4 };
println!("{}", k.alan()); // 12Methods gather the type's behaviour in one place and are called with dot syntax.
Automatic referencing
In the call k.alan(), Rust looks at the method signature and adds &k, &mut k or *k if needed. That's why no separate operator like C++'s -> is needed:
let k = Kutu { en: 3, boy: 4 };
let r = &k;
println!("{} {}", k.alan(), r.alan()); // 12 12
println!("{}", Kutu::alan(&k)); // full path: 12Practice Area method
For Kutu { en: u32, boy: u32 }, write the method fn alan(&self) -> u32 in an impl block. Print the result of k.alan() for Kutu { en: 3, boy: 4 }.
Starter code
struct Kutu {
en: u32,
boy: u32,
}
fn main() {
// buraya yaz
}Sample solution
struct Kutu {
en: u32,
boy: u32,
}
impl Kutu {
fn alan(&self) -> u32 {
self.en * self.boy
}
}
fn main() {
let k = Kutu { en: 3, boy: 4 };
println!("{}", k.alan());
}Expected output
12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>&self</code> short for?
- self: &Self Correct answer
- self: Self
- self: &mut Self
- this: &Kutu
Explanation: Inside impl Kutu, Self is an alias for the Kutu type; &self is the short way of writing self: &Self.
2 Attach the method
____ Kutu {
fn alan(&self) -> u32 {
self.en * self.boy
}
}
impl Kutu {
fn alan(&self) -> u32 {
self.en * self.boy
}
}
Explanation: Methods are written in an impl TypeName { ... } block.
3 Call and meaning
| Term | Meaning |
|---|---|
k.alan() |
Method call |
Kutu::alan(&k) |
Fully qualified call |
self.en |
The instance's field |
Self |
Alias for the type |