Movatterモバイル変換


[0]ホーム

URL:


self

Keywordself 

Source
Expand description

The receiver of a method, or the current module.

self is used in two situations: referencing the current module and markingthe receiver of a method.

In paths,self can be used to refer to the current module, either in ause statement or in a path to access an element:

usestd::io::{self, Read};

Is functionally the same as:

usestd::io;usestd::io::Read;

Usingself to access an element in the current module:

fnfoo() {}fnbar() {self::foo()}

self as the current receiver for a method allows to omit the parametertype most of the time. With the exception of this particularity,self isused much like any other parameter:

structFoo(i32);implFoo {// No `self`.fnnew() ->Self{Self(0)    }// Consuming `self`.fnconsume(self) ->Self{Self(self.0+1)    }// Borrowing `self`.fnborrow(&self) ->&i32 {&self.0}// Borrowing `self` mutably.fnborrow_mut(&mutself) ->&muti32 {&mutself.0}}// This method must be called with a `Type::` prefix.letfoo = Foo::new();assert_eq!(foo.0,0);// Those two calls produces the same result.letfoo = Foo::consume(foo);assert_eq!(foo.0,1);letfoo = foo.consume();assert_eq!(foo.0,2);// Borrowing is handled automatically with the second syntax.letborrow_1 = Foo::borrow(&foo);letborrow_2 = foo.borrow();assert_eq!(borrow_1, borrow_2);// Borrowing mutably is handled automatically too with the second syntax.letmutfoo = Foo::new();*Foo::borrow_mut(&mutfoo) +=1;assert_eq!(foo.0,1);*foo.borrow_mut() +=1;assert_eq!(foo.0,2);

Note that this automatic conversion when callingfoo.method() is notlimited to the examples above. See theReference for more information.


[8]ページ先頭

©2009-2026 Movatter.jp