Home
Rust
self Keyword Use
Updated Aug 21, 2025
Dot Net Perls

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.

Example

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.

Part 1 We have a public new function that returns a new instance of the Test struct by returning Self.
Part 2 If a method modifies the instance it is called upon, we must use a mut reference.
Part 3 As always in Rust a reference is by default immutable, and with immutable references we cannot modify any fields.
Part 4 We can have associated methods in an 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 notes

There 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.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 21, 2025 (new).
Home
Changes
© 2007-2025 Sam Allen