structs and methods

struct Target {
    host: String,
    port: u16,
}

impl Target {
    fn new(host: &str, port: u16) -> Self {
        Self { host: host.to_string(), port }
    }

    fn endpoint(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }
}

That compiled and ran

impl blocks

Methods live in impl blocks &self borrows the instance &mut self mutably borrows it No self receiver means a static method

Field init shorthand

Self { host: host.to_string(), port }

When the field and variable share a name, write it once Small thing, but it removes noise

Tuple structs

struct Port(u16);

Useful for newtypes A Port is not a u16 in the type system, even though it wraps one That distinction prevents mixing units

Builder pattern

Rust has no constructor overloads The builder pattern is the usual answer It is more verbose than a constructor, but the intent is explicit

Next

Enums and pattern matching in 06 enums and match

Posted