>

Structures

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:

Top

1
2
3
4
5
6
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64
}

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_count rather than SignInCase.

To initialize an instance of the struct:

1
2
3
4
5
6
7
8
fn main() {
    let user = User{
        active: true,
        username: String::from("apollo"),
        email: String::from("[email protected]"),
        sign_in_count: 1,
    };
}

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fn main() {
    let mut user = User{
        active: true,
        username: String::from("apollo"),
        email: String::from("[email protected]"),
        sign_in_count: 1,
    };

    user.sign_in_count += 1;
}

The Tuple Structure:

Top

1
struct Point(i32, i32);

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:

1
2
3
4
fn main() {
    let p = Point(3, 5);
    println!("x: {} y: {}", p[0], p[1]);
}

The Unit Structure:

Top

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.

1
2
3
4
5
6
7
// Making the unit-like structure "AlwaysEqual"
struct AlwaysEqual;

fn main() {
    // Initiating the unit-like struct
    let subject = AlwaysEqual;
}

2023-10-24