Intro

A struct in Rust is used to encapsulate data. structs can have fields , associated functions and methods .

rust
// Example struct definition.
struct StuffAndThings {
    stuff: String, // struct field
    things: u8,
}

// Instantiate an immutable struct.
let sat = StuffAndThings {
    stuff: String::from("stuff"),
    things: 8,
};

// Access the structs fields.
println!("{}", sat.stuff); // => stuff
println!("{}", sat.things); // => 8

// Instatiate a mutable struct.
let mut sat1 = StuffAndThings::new();

// Set the fields on a mutable struct.
sat1.stuff = String::from("blah");
sat1.things = 42;

// Access the structs fields.
println!("{}", sat1.stuff); // => blah
println!("{}", sat1.things); // => 42

Associated Function

Associated functions are tied to an instance of a struct and are usually used as constructors during instantiation.

rust
// Implement a `new` associated funtion that is 
// used to instatiate `StuffAndThings` with default values.
impl StuffAndThings {
    // `Self` is syntastic sugar in-place of the struct 
    // name: `StuffAndThings`
    fn new() -> Self { 
        Self {
            stuff: String::from("no stuff"),
            things: 0,
        }
    }
}

// Instantiate a struct with default values.
let sat = StuffAndThings::new();

// Access a structs fields.
println!("{}", sat.stuff); // => no stuff
println!("{}", sat.things); // => 0

Methods

Methods add behaviour to a struct.

rust
// Implement a `show` method on the `StuffAndThings` struct.
impl StuffAndThings {
    // `&self` is syntastic sugar for `self: &Self`
    // `StuffAndThings` is the (&self) caller object.
    fn show(&self) -> String {
        format!("stuff: {} | things: {}", self.stuff, self.things)
    }
}

// Instantiate a struct with default values.
let sat = StuffAndThings::new();

// Call the method.
println!("{}", sat.show()); // => stuff: no stuff | things: 0

Considerations

  • When instantiating a struct , all fields must be defined.
  • The new associated function is a Rust convention to construct a struct with default values.
  • In an associtated function, using Self in-place of the struct name is syntastic sugar.
  • Methods take &self as their first parameter, where &self is the calling object.
# rust