DEV Community

Luke Hinds
Luke Hinds

Posted on

Impl and Self

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay