self parameter
- Rust course
- Beginner
- Lesson 72/115
- 4 min
Call methods through &self and access fields.
The self parameter
self can be taken in three forms, and each is a different contract:
&self— reads; the most common.&mut self— modifies.self— consumes the instance; it can't be used after the call.
impl Kutu {
fn kapsar(&self, d: &Kutu) -> bool {
self.en > d.en && self.boy > d.boy
}
fn ozet(self) -> String {
format!("{}x{}", self.en, self.boy)
}
}Extra parameters
Normal parameters come after self. To read another instance, it is taken by reference too:
let buyuk = Kutu { en: 8, boy: 6 };
let kucuk = Kutu { en: 3, boy: 4 };
println!("{}", buyuk.kapsar(&kucuk)); // true
println!("{}", kucuk.kapsar(&buyuk)); // falseMethod names can match field names: k.en is the field, k.en() calls the method. This is the common way to write getters.
Practice Containment check
Inside impl Kutu, write fn kapsar(&self, d: &Kutu) -> bool: true if both width and height are larger. For a = Kutu { en: 8, boy: 6 } and b = Kutu { en: 3, boy: 4 }, print the results of a.kapsar(&b) and b.kapsar(&a).
Starter code
struct Kutu {
en: u32,
boy: u32,
}
fn main() {
// buraya yaz
}Sample solution
struct Kutu {
en: u32,
boy: u32,
}
impl Kutu {
fn kapsar(&self, d: &Kutu) -> bool {
self.en > d.en && self.boy > d.boy
}
}
fn main() {
let a = Kutu { en: 8, boy: 6 };
let b = Kutu { en: 3, boy: 4 };
println!("{} {}", a.kapsar(&b), b.kapsar(&a));
}Expected output
true false
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 After <code>let s = k.ozet();</code>, can <code>k.alan()</code> be called? (<code>fn ozet(self)</code>, Kutu isn't Copy)
- Yes
- Only if k is mut
- ozet doesn't compile
- No: k was moved into ozet Correct answer
Explanation: A method taking self takes ownership. Conversion methods (into_*, ozet) are usually like this.
2 A reading method
fn kapsar(____, d: &Kutu) -> bool {
self.en > d.en && self.boy > d.boy
}
fn kapsar(&self, d: &Kutu) -> bool {
self.en > d.en && self.boy > d.boy
}
Explanation: A method that only reads takes &self; the instance can still be used after the call.
3 Signature and effect
| Term | Meaning |
|---|---|
fn f(&self) |
Reads |
fn f(&mut self) |
Modifies |
fn f(self) |
Consumes |
fn f() |
Associated function |