MOCKSTACKS
EN
Questions And Answers

More Tutorials








RUST Struct

Structs are similar to tuples. The pieces of a struct can be different types. You’ll name each piece of data so it’s clear what the values mean. As a result of these names, structs are more flexible than tuples: you don’t have to rely on the order of the data to specify or access the values of an instance.

To define a struct, we enter the keyword struct and name the entire struct. A struct’s name should describe the significance of the pieces of data being grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which we call fields.

Example of RUST Struct


struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

Use of RUST Struct

To use a struct after we’ve defined it, we create an instance of that struct by specifying concrete values for each of the fields.

   let user1 = User {
        active: true,
        username: String::from("someusername123"),
        email: String::from("someone@example.com"),
        sign_in_count: 1,
    };


Accesing RUST Struct Attribute

To get a specific value from a struct, we can use dot notation. If we wanted just this user’s email address, we could use user1.email

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

Complete Example of RUST Struct


struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main(){
  let mut user1 = User {
        active: true,
        username: String::from("mockstacksUser"),
        email: String::from("someone@mockstacks.com"),
        sign_in_count: 1,
    };

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

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

output of above code

My user email: anotheremail@mockstacks.com


Conclusion

In this page (written and validated by ) you learned about Rust Struct . What's Next? If you are interested in completing Rust tutorial, your next topic will be learning about: Rust File handling - Read - Write.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.