Location>code7788 >text

Rust Programming and Project Practice - Structures

Popularity:189 ℃/2024-11-08 10:49:49

Rust Programming and Project Combat (Zhu Wenwei, Li Jianying) [Abstract Book Review Try reading] - Jingdong Book ()

In Rust, Struct is a custom data type that allows us to combine multiple related values to form a more complex data structure. Structs are widely used in Rust to organize and manage data with flexibility and powerful expressive capabilities. This section will introduce the concepts, definition syntax, methods, and related features of structures in Rust in detail, and provide code examples to help readers better understand how to use structures.

8.3.1 Definition of Structures

Structures and tuples in Rust can both bundle together a number of pieces of data of not necessarily the same type to form a whole, but each member of a structure and itself has a name so that you don't have to remember subscripts when accessing its members. Tuples are often used for undefined multi-value passing, while structures are used to standardize commonly used data structures. Each member of a structure is called a "field".

In Rust, we can define a structure using the struct keyword. Structs allow us to define multiple fields (Fields), each with its own type and name. By combining fields together, you can create your own data types to better represent and manipulate data. Below is an example of a simple structure definition:

struct Point {
    x: i32,
    y: i32,
}

In the above example, we defined a structure named Point with two fields x and y, each an integer of type i32. Look at another structure definition:

struct Site {
    domain: String,
    name: String,
    nation: String,
    found: u32
}

Note: If you commonly use C/C++, remember that in Rust the struct statement is only used for definitions, no instances can be declared, no ";" symbols are needed at the end, and each field definition is separated by a ",".

8.3.2 Instantiating Structures

Once a structure is defined, concrete objects can be created by instantiating the structure. Structures can be instantiated in the following two ways:

1) Declarative instantiation

let p = Point { x: 10, y: 20 };

In the above example, we used the definition of the Point structure to create an instance named p, specifying the values of the fields x and y. The example above shows that we have used the definition of the Point structure to create an instance named p, with the values of the fields x and y specified.

2) Variable instantiation

If you need to modify the value of a field in a structure, you can add mut to the definition of the structure variable with the following code:

let mut p = Point { x: 10, y: 20 };
 = 30;
 = 40;

In the above example, we created a mutable instance p and modified the values of the fields x and y.

Rust is influenced in many places by JavaScript, using the key: value syntax of JSON objects when instantiating structures, for example:

let mysite = Site {
    domain: String::from(""),
    name: String::from("qq"),
    nation: String::from("China"),
    found: 2024
};

If you don't understand the JSON object, you can leave it alone and just memorize the format:

Structure class name {
    field name : field value, .
    ...
}

This has the advantage of not only making the program more intuitive, but also eliminating the need to enter the values of the members in the order in which they are defined. If the structure being instantiated has field names that are the same as existing variable names, this can simplify writing:

let domain = String::from("");
let name = String::from("qq");
let runoob = Site {
    domain,  // Equivalent to domain : domain,
    name,    // Equivalent to name : name,
    nation: String::from("China"),
    traffic: 2024
};

In the case where you want to create a new instance of a structure in which most of the properties need to be set to be the same as the properties of an existing structure, and only need to change the value of one or two of the fields, you can use the structure update syntax:

let site = Site {
    domain: String::from(""),
    name: String::from("qq"),
  ..qq
};

Note: . .qq may not be followed by a comma. This syntax does not allow copying another instance of the structure unchanged, meaning that the value of at least one field is reset before the value of the other instance can be referenced.

8.3.3 Methods of Structures
In Rust, structures can have their own methods. A method is a function associated with a structure that can be called through a structure instance. The following is an example of a struct method:

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {                     //Use the keyword impl to define one or more methods of a structure
    fn area(&self) -> u32 {          //Define specific functions with the keyword fn
         * 
    }
}

fn main() {
    let rect = Rectangle { width: 10, height: 20 };
    let area = ();
    println!("Area: {}", area);
}

In the above example, we define a structure called Rectangle and implement an area method for it to calculate the area of the rectangle. In the main function, we create a Rectangle instance, rect, and then calculate the area of the rectangle by calling the area method and printing it out.

8.3.4 Associative Functions for Structures

In addition to instance methods, structures can also define Associated Functions. Associated functions are functions that are directly associated with a structure and do not need to be called through a structure instance. The following is an example of an Associated Function:

struct Circle {
    radius: f64,
}

impl Circle {
    fn new(radius: f64) -> Circle {
        Circle { radius }
    }

    fn area(&self) -> f64 {
        std::f64::consts::PI *  * 
    }
}

fn main() {
    let circle = Circle::new(5.0);
    let area = ();
    println!("Area: {}", area);
}

In the above example, we define a structure named Circle and implement an association function new for it to create a new instance of Circle. In the main function, we create a Circle instance circle by calling the Circle::new association function and then calculate the area of the circle by calling the area method and print it out.

8.3.5 Properties of Structures

Rust's structures are characterized by two properties: the Tuple Struct and the Unit-Like Struct.

A tuple structure is a special type of structure that has no named fields, only the type of the field. Tuple structs are defined using parentheses instead of curly braces. For example:

struct Color(i32, i32, i32);

In the above example, we have defined a tuple structure named Color, which contains 3 fields of type i32.

A class unit structure is a structure with no fields, similar to an empty tuple. For example:

struct Empty;

In the above example, we defined a class unit structure named Empty.