What the different self and Self in Rust
2023年11月21日小于 1 分钟
What the different self and Self in Rust
In Rust, self and Self have distinct meanings and are used in different contexts:
self:- Usage:
selfis used as the first parameter of an instance method of a struct or enum. It represents the instance of the struct or enum on which the method is called. - Variants: It has three forms:
self- Used when the method consumes the struct (takes ownership).&self- Used when the method only needs a reference to the struct, without taking ownership.&mut self- Used when the method needs a mutable reference to the struct.
- Example: In a method definition like
fn do_something(&self),selfrefers to the instance of the struct.
- Usage:
Self:- Usage:
Self(note the capital 'S') is an alias for the type of the current trait or impl block. - Context: It's typically used in trait definitions and their impl blocks. In a trait,
Selfrefers to the type that implements the trait. In an impl block,Selfrefers to the type that the block is implementing traits for or adding methods to. - Example: In a trait definition like
trait Example { fn clone(&self) -> Self; },Selfrefers to the type that implements theExampletrait.
- Usage:
Example to Illustrate the Difference:
struct MyStruct;
impl MyStruct {
// Here, self refers to the instance of MyStruct
fn instance_method(&self) {
println!("Called on an instance of MyStruct");
}
// Here, Self refers to the MyStruct type itself
fn new() -> Self {
MyStruct
}
}In the above example:
&selfininstance_methodrefers to the instance ofMyStruct.Selfinnewis used as a type name, referring toMyStruct. It's a way to avoid repeating the type nameMyStruct.