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. This is a structure definition: 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. Rust is influenced by JavaScript in many places. When instantiating a structure, it uses the JSON object’s If you don’t understand, 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: 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: Note: There can be no commas after 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: “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: Running result: 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 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. 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: As shown in the first line: be sure to import the debug library You can use another placeholder if you have more attributes Output result: 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. 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 Calculate the area of a rectangle: Output result: Please note that you do not need to fill in when calling the structure method An example of multiple parameters: Running result: This program calculates The reason why “structure method” is not called “structure function” is because the name “function” is left to this function: it is in the This function does not depend on the instance, but you need to declare whereto use it Always in use. Running result: Tip: structure A structure can be used only as a symbol without any member: We call this structure without a body a Unit Struct. 7.13.1. Structure definition #
struct Site {
domain: String,
name: String,
nation: String,
found: u32
}
7.13.2. Structure instance #
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
};
JSON
object, you can ignore it and remember the format:Structure class name {
Field Name: Field Value,
...
}
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
};
let site = Site {
domain: String::from("www.runoob.com"),
name: String::from("RUNOOB"),
..runoob
};
..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. 7.13.3. Tuple structure #
struct Color(u8, u8, u8);
struct Point(f64, f64);
let black = Color(0, 0, 0);
let origin = Point(0.0, 0.0);
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);
}
black = (0, 0, 0)
origin = (0, 0)
7.13.4. Ownership of structure #
String
type without using the
&str
reason. 7.13.5. Output structure #
Example #
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle { width: 30, height: 50 };
println!("rect1 is {:?}", rect1);
}
#[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 }
{:#?}
.rect1 is Rectangle {
width: 30,
height: 50
}
7.13.6. Structural body method #
this
represents the instance of the operation.
&self
there is no need to declare the type, because
self
not a style, but a keyword.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());
}
rect1's area is 1500
self
, this is for the convenience of useExample #
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));
}
false
rect1
is it wider than
rect2
. 7.13.7. Structure correlation function #
impl
, but
&self
parameters is not in the block. .
impl
in the block.
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);
}
Rectangle { width: 30, height: 50 }
impl
blocks can be written several times, and the effectis equivalent to the stitching of their contents! 7.13.8. Unit structure #
struct UnitStruct;