Member-only story
Understanding Rust Structs: Data Grouping, Methods, and Static Functions
Structures in Rust: Similar to Classes or Dictionaries
In Rust, a struct
is similar to classes in OOP languages (like Java or C++) or to dictionaries in languages like Python. A struct
groups related fields together, much like key-value pairs, allowing you to create a cohesive data structure.
Here’s an example of a Pet
struct in Rust:
struct Pet {
name: String,
age: u8,
breed: String,
}
Instantiating an Object from a Struct
To create an instance of the Pet
struct, you can assign values to each field like so:
let cat = Pet {
name: String::from("Sunny"),
age: 1,
breed: String::from("Maine Coon"),
};
However, if you try to print the struct instance directly, you’ll run into an issue:
println!("{:?}", cat); // Pet` cannot be formatted using `{:?}`
Printing Structs: Deriving the Debug
Trait
The reason printing doesn’t work right away is that Rust needs to know how to format the struct’s output. By adding the #[derive(Debug)]
attribute to the struct definition, we automatically implement…