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,
}
We can then implement the struct as a type:
impl RandomInfo {
    fn new() -> RandomInfo {
        RandomInfo {
            some_bool: true,
            some_int: 42,
        }
    }
}
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,
        }
    }
}
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);
}
    
Top comments (0)