Member-only story
How to Use Rust Structs, Methods (Impl), and Traits With Examples
Rust by example
I always find that when learning a programming language, it is helpful when the example provided reflects real-world use cases. Unfortunately, these kinds of examples are not provided or are hard to find.
For example, the “Defining and Instantiating Structs” section in The Rust Programming Language book provides an example where one defines Structs and then creates an instance of that Struct by specifying a value for each of the fields in the code itself. In the real world, no programmer would do this for an obvious reason. It also does not explain how one would use Structs in their code.
Since I need a featured image for this article, the following is an example of Structs.

Before diving into an article, let’s get some housekeeping out of way first by providing an overview of Structs and use cases for using Structs in your code. All source codes are also available on GitHub => https://github.com/sungkim11/rust-struct.
Structs
A struct is a user-defined type that we can use to store one or more variables of different types. A struct allows us to group related code together and models our application after entities in the real world per https://www.koderhq.com/tutorial/rust/struct/.
An example of a struct is:
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
Where would you use Structs?
A good use case for using structs would be calling a REST API where the response is returned in JSON format. An example of JSON format is:
{
"active": true
"username": "user",
"email": "user@user.com",
"sign_in_count": 2
}
As you can see from above, Structs are similar to JSON where you are able to map JSON values to a Struct. In the real world, structs are used to parse JSON values. It is usually called Deserialize/Decode to convert JSON to struct and…