What is the difference between self and Self?

While implementing methods for structures, I came across self, &self, &mut self, Self, &Self, &mut Self. What is the difference between them?

&self is syntax sugar for self: &Self. The same applies for all the other variants that you mentioned.

2 Likes

In addition to what @moy2010 said, Self:: can also be used to call static functions, i.e.

impl Foo {
  fn hello() -> u32 { 42 }

  fn blah(&self) {
    ..
    Self::hello();
    ...
  }
}

3 Likes

Self is a reserved alias name for the implementing type.

//   vvvvvv
impl MyType
//             vvvvvv
impl Trait for MyType

self is a reserved name for the receiever variable, be it Self or &Self or Arc<Self>, etc, as per the previous replies.

3 Likes

self is a variable name and Self is a type name.

4 Likes

The description of self in the book may also help.

2 Likes

I've figured out the difference between them. When we implement methods for structures, we often see &self and &mut self. It can often be deduced through the following path:
&self => self: &Self => self: &"struct name"

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.