Copy the example while reading the documentation for the first time, and can cover two large chapters in a day. Now taking notes, but can only cover half a chapter in two days. 😔
Mutability#
If you want to modify the value of a certain field, the struct instance must be mutable.
Struct Update Syntax#
Struct update syntax is similar to the Spread syntax in JavaScript, but it can only be used to create a new instance of the same struct using the old instance. Why use this syntax? Can't we just modify the fields of a mutable instance directly? Is it because we don't want to create a mutable instance and instead perform a merge operation, immutability?
let user2 = User {
age: 19,
..user1
}
There are also two special struct definitions:
// Tuple struct
struct Color(i32, i32, i32);
// Unit struct
struct Something;
Understanding#
- Compared to tuples, structs provide readable identifiers for composite values. TypeScript also has the concept of tuples, which are arrays of finite length. Arrays are special objects with numeric indexes as keys, and in some scenarios, they can be used instead of objects. However, specifying keys makes the meaning of fields easier to understand.
- Allows a collection of values to be an abstract entity, and methods and associated functions can be implemented for this collection.
Methods and Associated Functions#
You can implement [[functions]] associated with a struct, called associated functions, which are similar to static methods in JavaScript classes. If the first parameter of an associated function accesses the instance context through self
, it is called a method.
impl User {
// Associated function
fn new() -> Self {
Self {
name: String::from(""),
age: 1,
}
}
// Instance method
fn get_name(&self) -> &str {
&self.name
}
// Mutable instance method
fn set_name(&mut self, name: String) {
self.name = name
}
}
When defining a method, the first parameter &self
is a shorthand for self: &Self
. You can also remove the &
to take ownership of the instance.