struct#
Basic usage of struct#
Let’s learn how to use Structs in Rust.
The struct Person { ~~~ } part in the following example defines a struct.
The Person struct has the fields name, age, and is_student, and each field has its type defined.
struct Person {
name: String,
age: i32,
is_student: bool,
}
fn main() {
let mut person = Person {
name: String::from("semonan.com"),
age: 12,
is_student: true,
};
println!("{}, {}, {}", person.name, person.age, person.is_student);
person.age = 13;
println!("{}, {}, {}", person.name, person.age, person.is_student);
}A struct must be instantiated to be used, as shown with let mut person = Person { ~~~ }.
In the example above, the instance is created as mutable so that the values of each field can be changed.
You can read the values of the struct with code like person.name, person.age, person.is_student.
You can change a value with code like person.age = 13;.