Post

Structs

Structs

Custom datatype that packages related data. A struct’s name should describe the significance of the pieces of data being grouped together

There are 3 types:

  • Normal Structs
  • Tuple Structs
  • Unit Structs

We use a struct keyword to define a structure.

For example

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

Using the User struct.

1
2
3
4
5
6
7
fn main(){
let mut user1 = User{
    active:true,
    username:String::from("someusername123"),
    email:String::from("someone@example.com"),
    sign_in_count:1,
};

To get a specific value from a struct, we use dot notation.

For example, to access this user’s email address, we use user1.email.

If the instance of the struct is mutable, we can change a value in the struct using the dot notation.

For example, to change the value of the email, we use

user1.email = String::from("test1@gmail.com");

We can create a new instance of a struct that includes most of the values from another instance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 let user2 = User {
        active: user1.active,
        username: user1.username,
        email: String::from("another@example.com"),
        sign_in_count: user1.sign_in_count,
    };

-----Or----
let user  = User{

    email:String::from("another@example.com"),
    ..user1
}

}


tuple structs

1
2
3
4
5
6
7
8
9
struct Color(i32,i32,i32);
struct Point(i32,i32,i32);


fn main(){

     let black = Color(0,0,0);
     let origin = Point(0,0,0);
}

Unit structs

They have no fields

1
2
3
4
5
struct AlwaysEqual;

fn main() {
    let subject = AlwaysEqual;
}
This post is licensed under CC BY 4.0 by the author.