published: 19th of February 2022
A struct in Rust is used to encapsulate data. structs can have fields , associated functions and methods .
// 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 functions are tied to an instance of a struct and are usually used as constructors during instantiation.
// 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 add behaviour to a struct.
// 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
https://www.manning.com/books/rust-in-action
https://www.udemy.com/course/ultimate-rust-crash-course/
https://doc.rust-lang.org/rust-by-example/custom_types/structs.html
https://doc.rust-lang.org/rust-by-example/fn/methods.html
https://doc.rust-lang.org/reference/items/associated-items.html