How to Use the Self Type in Rust

Use Self in Rust impl blocks as a shorthand for the current type to simplify method signatures and return types.

Use Self as a type alias for the implementing type within an impl block to avoid repeating the type name. This is especially useful when defining methods that return the same type or take it as an argument.

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn can_hold(&self, other: &Self) -> bool {
        self.width > other.width && self.height > other.height
    }

    fn new(width: u32, height: u32) -> Self {
        Rectangle { width, height }
    }
}