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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

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