Understanding Self in Rust
In Rust, Self is a special type alias that refers to the type of the current trait or implementation block. It is commonly used in trait definitions and implementations to refer to the type that is implementing the trait.
trait MyTrait { fn new() -> Self; fn describe(&self) -> String; } struct MyStruct { name: String, } impl MyTrait for MyStruct { fn new() -> Self { Self { name: String::from("MyStruct"), } } fn describe(&self) -> String { format!("This is {}", self.name) } } fn main() { let instance = MyStruct::new(); println!("{}", instance.describe()); }
- The
MyTraittrait defines two methods:newanddescribe. - The
newmethod returns an instance of the type that implements the trait, denoted bySelf. - The
describemethod takes a reference toselfand returns a description string. - The
MyStructstruct implements theMyTraittrait, usingSelfto refer to its own type within the implementation.
This allows for more flexible and reusable code, as Self can adapt to the type that is implementing the trait.