Self
Every programming language needs a way to indicate "this type instance" and in Rust, we have the self
-keyword. This is the same as the this
-keyword in other languages.
With the uppercase Self
, we can reference the current type, and the lowercase self
references the current type instance. In an impl
block, we often have a first parameter of type self
.
Here are some uses of the self
and Self
keyword and type. In practice the difference between the two identifiers make sense, as type names are always uppercased.
struct
by returning Self
.mut
reference.impl
block, and we can reference them with Self::info()
syntax.struct Test { element: usize, } impl Test { // Part 1: this creates a new Test instance and returns Self. pub fn new() -> Self { Self { element: 1 } } // Part 2: this acts on a mutable self reference. pub fn modify(&mut self) { self.element *= 3; } // Part 3: this acts on an immutable self reference (no modifications allowed) pub fn print(&self) { Self::info(); println!("{}", self.element); } // Part 3: this is an associated method, so we call it with Self::info(). fn info() { println!("INFO"); } } fn main() { // Use the Test struct and its impl. let mut t = Test::new(); t.modify(); t.print(); }INFO 3
Self
notesThere is no difference between the this
-keyword and the self
-keyword in practical usage. Other languages can even use keywords like "me" which seems less elegant.
With Rust it is common to use impl
blocks to define the implementation methods for a struct
. This is the same as member methods in a class
in object-oriented languages.