Impl and Self

Luke Hinds - Nov 25 '22 - - Dev Community

What is Self, not in a philosophical sense, but what is Self in rusts world?

We create a simple Struct which defines a bool and an int.

struct RandomInfo {
    some_bool: bool,
    some_int: i32,
}
Enter fullscreen mode Exit fullscreen mode

We can then implement the struct as a type:

impl RandomInfo {
    fn new() -> RandomInfo {
        RandomInfo {
            some_bool: true,
            some_int: 42,
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

However, we don't actually need to specify the type, the compiler is able to infer the type itself, so we can instead use Self

impl RandomInfo {
    fn new() -> Self {
        Self {
            some_bool: true,
            some_int: 42,
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Putting it all together

struct RandomInfo {
    some_bool: bool,
    some_int: i32,
}

impl RandomInfo {
    fn new() -> Self {
        Self {
            some_bool: true,
            some_int: 42,
        }
    }
}

fn main() {
    let info = RandomInfo::new();
    println!("some_bool: {}", info.some_bool);
    println!("some_int: {}", info.some_int);
}
Enter fullscreen mode Exit fullscreen mode
. . . . .