Rust Programming: Defining and Instantiating Structs

0

Defining and instantiating structs are two important concepts in Rust. To define a struct, we use the `struct` keyword and then specify the name of the struct and the names and types of the fields. To instantiate a struct, we create a variable of the struct type and then specify the values for each of the fields. For example, the following code defines a struct called `User` with four fields:

struct User {

    active: bool,

    username: String,

    email: String,

    sign_in_count: u64,

}

To instantiate a `User` struct, we can use the following code:

let user1 = User {

    active: true,

    username: String::from("someusername123"),

    email: String::from("someone@example.com"),

    sign_in_count: 1,

};

We can then access the values of the `User` struct using dot notation. For example, the following code prints the value of the `email` field of the `user1` struct:

println!("{}", user1.email);

We can also change the values of the fields of a `User` struct using dot notation. For example, the following code changes the value of the `email` field of the `user1` struct:

user1.email = String::from("anotheremail@example.com");

We can also construct a new instance of a struct as the last expression in the function body to implicitly return that new instance. For example, the following function constructs a new `User` struct and returns it:

fn build_user(email: String, username: String) -> User {

    User {

        active: true,

        username: username,

        email: email,

        sign_in_count: 1,

    }

}

This function can then be used to create new `User` structs, as shown in the following code:

let user1 = build_user(String::from("someone@example.com"), String::from("someusername123"));

Post a Comment

0Comments
Post a Comment (0)