Rust structure


Release date:2023-11-08 Update date:2023-11-08 Editor:admin View counts:225

Label:

Rust structure

Both Struct and Tuple in Rust can tie together several data of different types to form a whole, but each member of the structure and itself has a name, so you don’t have to remember the subscript when accessing its members. Tuples are often used for undefined multivalued transmission, whilestructures are used to standardize commonly used data structures. Each member of the structure is called a field.

Structure definition

This is a structure definition:

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

Note: if you use CCompact Clippers, please remember that in Rust ``struct``statement is only used for definition, the instance cannot be declared, theend is not required; symbols, and each field is separated after definition.

Structure instance

Rust is influenced by JavaScript in many places. When instantiating a structure, it uses the JSON object’s key : value syntax to implement the definition:

Example

let runoob = Site {
    domain: String::from("www.runoob.com"),
    name: String::from("RUNOOB"),
    nation: String::from("China"),
    found: 2013
};

If you don’t understand, JSON object, you can ignore it and remember the format:

Structure class name {
    Field Name: Field Value,
    ...
}

The advantage of this is that it not only makes the program more intuitive, but also does not need to enter the values of the members in the defined order.

If the structure you are instantiating has the same field name as the existing variable name, you can simplify the writing:

Example

let domain = String::from("www.runoob.com");
let name = String::from("RUNOOB");
let runoob = Site {
    domain,  // Equivalent to domain : domain,
    name,    // Equivalent to name : name,
    nation: String::from("China"),
    traffic: 2013
};

There is a situation where you want to create a new instance of a structure,and most of the properties need to be set to be the same as an existing structure property. You only need to change the value of one or two of the fields, and you can use the structure to update the syntax:

let site = Site {
    domain: String::from("www.runoob.com"),
    name: String::from("RUNOOB"),
    ..runoob
};

Note: There can be no commas after ..runoob. This syntax does not allow you to copy another instance of the structure invariably, meaning thatat least one field’s value is reset to reference the value of another instance.

Tuple structure

There is a simpler way to define and use structures: tuple structures.

A tuple structure is a form that is a tuple structure.

It differs from tuples in that it has a name and a fixed type format. It exists to deal with simple data that needs to be defined (often used) and does not want to be too complex:

struct Color(u8, u8, u8);
struct Point(f64, f64);

let black = Color(0, 0, 0);
let origin = Point(0.0, 0.0);

“Color” and “point coordinates” are two commonly used data types, but Rust won’t leave this problem if you write curly braces and two names in instantiation at the expense of convenience for readability. Tuple structureobjects are used in the same way as tuples, through. And subscript to access:

Example

fn main() {
    struct Color(u8, u8, u8);
    struct Point(f64, f64);
    let black = Color(0, 0, 0);
    let origin = Point(0.0, 0.0);
    println!("black = ({}, {}, {})", black.0, black.1, black.2);
    println!("origin = ({}, {})", origin.0, origin.1);
}

Running result:

black = (0, 0, 0)
origin = (0, 0)

Ownership of structure

The structure must have ownership of the field value, because all fields arereleased when the structure fails.

This is why the case in this chapter is used String type without using the &str reason.

However, this does not mean that reference fields are not defined in the structure, which needs to be achieved through the “lifecycle” mechanism.

However, it is difficult to explain the concept of “life cycle”, so it canonly be explained in later chapters.

Output structure

In debugging, it is useful to show a complete instance of a structure. But if we write a format manually, it will be very inconvenient. So Rust provides a convenient way to output an entire structure:

Example

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    println!("rect1 is {:?}", rect1);
}

As shown in the first line: be sure to import the debug library #[derive(Debug)] , and then in println and print , you can use it in macros. The {:?} placeholder outputs an entire structure:

rect1 is Rectangle { width: 30, height: 50 }

You can use another placeholder if you have more attributes {:#?} .

Output result:

rect1 is Rectangle {
    width: 30,
    height: 50
}

Structural body method

The method (Method) is similar to the function, except that it isused to manipulate the structure instance.

If you have learned some object-oriented languages, you must be well aware that functions are generally placed in class definitions and used in functions. this represents the instance of the operation.

The Rust language is not object-oriented, as can be seen from the innovationof its ownership mechanism. But the precious idea of object-oriented can beimplemented in Rust.

The first parameter of the structure method must be &self there is no need to declare the type, because self not a style, but a keyword.

Calculate the area of a rectangle:

Example

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

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}
fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    println!("rect1's area is {}", rect1.area());
}

Output result:

rect1's area is 1500

Please note that you do not need to fill in when calling the structure method self , this is for the convenience of use

An example of multiple parameters:

Example

struct Rectangle {
    width: u32,
    height: u32,
}
impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
    fn wider(&self, rect: &Rectangle) -> bool {
        self.width > rect.width
    }
}
fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    let rect2 = Rectangle { width: 40, height: 20 };
    println!("{}", rect1.wider(&rect2));
}

Running result:

false

This program calculates rect1 is it wider than rect2 .

Structure correlation function

The reason why “structure method” is not called “structure function” is because the name “function” is left to this function: it is in the impl , but &self parameters is not in the block. .

This function does not depend on the instance, but you need to declare whereto use it impl in the block.

Always in use. String::from a function is a “correlation function”.

Example

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}
impl Rectangle {
    fn create(width: u32, height: u32) -> Rectangle {
        Rectangle { width, height }
    }
}
fn main() {
    let rect = Rectangle::create(30, 50);
    println!("{:?}", rect);
}

Running result:

Rectangle { width: 30, height: 50 }

Tip: structure impl blocks can be written several times, and the effectis equivalent to the stitching of their contents!

Unit structure

A structure can be used only as a symbol without any member:

struct UnitStruct;

We call this structure without a body a Unit Struct.

Powered by TorCMS (https://github.com/bukun/TorCMS).