Rust Reference ยท Keywords and Statements
Self and self
Reference for Rust Self and self: the self, &self, &mut self and self: Box<Self> receivers, the Self type alias in impl blocks and traits, and Self constructors.
Two keywords, two meanings. Lowercase self is the value a method is called on (the receiver), and it is also a path prefix meaning "the current module". Capitalized Self is an alias for the type being implemented: inside impl Point, Self means Point; inside a trait, it means "whatever type implements this trait".
The receiver is the first parameter of a method. self, &self and &mut self are shorthand for self: Self, self: &Self and self: &mut Self, and they decide whether the call consumes, reads or modifies the value.
impl Counter { fn new() -> Self { Self { n: 0 } } fn bump(&mut self) { self.n += 1; } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
fn a(self) {} // takes ownership fn b(&self) {} // shared borrow fn c(&mut self) {} // exclusive borrow fn d(mut self) {} // owned, mutable binding fn e(self: Box<Self>) {} // other receiver types fn f(self: &Rc<Self>) {} fn g() -> Self { todo!() } // associated function, no receiver
| Receiver | Same as | Use when |
|---|---|---|
self |
self: Self |
The method consumes the value (builders, into_*). |
&self |
self: &Self |
The method only reads. |
&mut self |
self: &mut Self |
The method changes the value in place. |
self: Box<Self>, Rc<Self>, Arc<Self>, Pin<&mut Self> |
Smart-pointer receivers, needed for some trait objects and async code. |
Usage notes
- A function without a receiver is an associated function, called as
Type::name().newis only a convention. Selfworks everywhere inside animpl: in signatures, as a struct literal (Self { .. }), for tuple structs (Self(..)), and for enum variants (Self::Variant).- Method call syntax auto-borrows.
c.get()becomesCounter::get(&c), adding&or&mutas the receiver requires. - Object safety: a trait with a method returning
Selfor without a receiver needswhere Self: Sizedto stay usable asdyn Trait. selfin paths:self::xis the current module,use self::Enum::*;is a common pattern, anduse a::{self, b}importsaanda::b.- Only the first parameter may be
self; it cannot appear later. - Naming a type in generics: inside
impl<T> Wrapper<T>,SelfisWrapper<T>, which shortens long types.