Structs
struct is custom data type that lets you package together and name multiple related values that make up a meaningfull group.
Defining Structs
structs are defining in the following way.
struct User {
active: bool,
username: String,
email: String,
sign_in_count: u64,
}
Instantiating Structs
Structs are instantiated by creating an instance of the struct with the concrete values.
let user1 = User {
active: true,
username: String::from("sherlock"),
email: Sting::from("sherlock@yahoo.com"),
sign_in_count: 1,
};
Accessing Struct Values
We use dot notation to access the specific value from the struct.
user1.email // sherlock@yahoo.com
Modifying The Struct
To change the value of struct first we need make user instance as mutable. let mut user1 = User {...}
.
we use the same dot notion to mutate the struct.
user1.email = String::from("jhon@yahoo.com")
.
Field Init Shorthand
When function parameters are passed down to the struct defnition there posiblitly repeating field names and function paramters. let say we have
funciton:
function build_user(username: String, email: string) -> User {
//This is called implicit return.
User {
active: true,
username: username,
email: email,
sign_in_count: 1,
}
}
AS u see we are repeating paramters and fields here.
With help of Field Init Shorthand we can write as follows
function build_user(username: String, email: string) -> User {
//This is called implicit return.
User {
active: true,
username,
email,
sign_in_count: 1,
}
}
Creating new instances from other instance with Struct Update Syntax(Spread syntax if you know JS).
let user2 = User {
email: String::from("holmes@yahoo.com");
...user1
};
It will have same the values of user1 and but email will be different.
Structs can be defined without the name and value fields.
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
Structs can also be defined unit-like without any field or types.
struct AlwaysEqual;
When to use structs
We use struct when we want to convey the meaning of our data in our code.
for example:
let say i have tuple like this
let rect1 = (30, 50)
which does not convey the what the values represent. In this case we can use struct to define our values with right structure.
let rect1 = Rectangle {
width: 30,
height: 50,
};
and the struct is
struct Rectangle {
width: u32,
height: u32,
}
Top comments (1)
The spread operation uses 2 dots in Rust, not the same as in JS