In many modern languages there comes a need for a programmer to store multiple pieces of data together. In languages like C++ that is called “encapsulation” because typically there is methods/functions that are defined to use that data in some way.
In Rust there are 3 “types” of structures or structs.
Adding functionality to structures with implementation block.
The regular struct:
| |
The above struct has a boolean field active, 2 String fields username and email, and a unsigned 64-bit integer (u64) sign_in_count.
This example shows that Rust prefers multiple word names in a camel_case like
sign_in_countrather thanSignInCase.
To initialize an instance of the struct:
| |
Take note that user in this example is immutable (See my Mutable & Immutable article).
So if we wanted to change anything within user (active, username, email or sign_in_count), we must make it mutable.
| |
The Tuple Structure:
| |
Rust also supports structs that look similar to tuples, called tuple structs. Tuple structs have the added meaning the struct name provides but don’t have names associated with their fields; rather, they just have the types of the fields.
In the above Point we access the 2 signed 32-bit integers (i32) by:
| |
The Unit Structure:
Unit-like structs can be useful when you need to implement a trait on some type but don’t have any data that you want to store in the type itself.
| |