struct

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;.

struct method

struct method#

What is a method?#

A method is essentially the same as a function, except that it is included within a struct.
Let’s learn how to define a method.
In the following example, a Person struct is defined as struct Person { ~~~ }.
In impl Person, impl stands for implementation.
The functions created inside impl { ~~~ } are methods.
A method is created with fn speak(self) { ~~~ }, where self is taken as the first parameter.
self refers to the struct itself, struct Person.
The first parameter of a method must be self; otherwise, a compile error will occur.
The line println!("hi, {}", self.name); prints self.name.
Here, self.name refers to name: String inside struct Person { name: String, }.
After creating an instance with let person = Person{ ~~~ };, you can call the method with person.speak().