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.
In addition to what @firebits.io said, Self:: can also be used to call static functions, i.e.
impl Foo {
fn hello() -> u32 { 42 }
fn blah(&self) {
..
Self::hello();
...
}
}
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.
self is a variable name and Self is a type name.
The description of self in the book may also help.
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.