Rust Structs
Structs (Struct) and tuples (Tuple) in Rust can both bundle several pieces of data of not necessarily the same type into a whole, but each member of a struct and the struct itself have a name, so you don't need to remember indices when accessing members. Tuples are often used for undefined multi-value passing, while structs are used to standardize common data structures. Each member of a struct is called a "field".
Structure Definition
This is a struct definition:
struct Site {
domain: String,
name: String,
nation: String,
found: u32
}
Note: if you often use C/C++, remember that in Rust the struct statement is only for definition, cannot declare instances, does not need a ; at the end, and each field definition is separated by a comma (,).
Struct Instances
Rust is influenced by JavaScript in many places; when instantiating a struct, it uses the JSON object 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 know about JSON objects, you can ignore it and just remember the format:
结构体类名 {
字段名 : 字段值,
...
}
The benefit of this is that it not only makes the program more intuitive, but also does not require entering member values in the order of definition.
If the struct being instantiated has field names that are the same as existing variable names, the writing can be simplified:
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 struct instance in which most properties need to be set the same as an existing struct's properties, and only one or two field values need to be changed; you can use struct update syntax:
let site = Site {
domain: String::from("www.runoob.com"),
name: String::from("RUNOOB"),
..runoob
};
Note: there must be no comma after ..runoob. This syntax does not allow copying another struct instance unchanged, meaning that you must reset the value of at least one field to reference the values of another instance.
Tuple Structs
There is a simpler way to define and use structs:Tuple Structs。
A tuple struct is a struct in the form of a tuple.
The difference from a tuple is that it has a name and a fixed type format. Its purpose is to handle simple data that needs a defined type (frequently used) but 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 if instantiating them requires writing curly braces and two names just for readability at the cost of convenience, Rust does not leave this problem. Tuple struct objects are used in the same way as tuples, accessed via . and indices:
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)
Struct Ownership
A struct must hold ownership of its field values, because when the struct becomes invalid it releases all its fields.
This is why the examples in this chapter use the String type rather than &str.
But this does not mean that reference-type fields cannot be defined in a struct; this needs to be achieved through the "lifetime" mechanism.
But it is still difficult to explain the "lifetime" concept now, so it can only be explained in later chapters.
Printing Structs
In debugging, it is very useful to display a struct instance completely. But if we manually write a format it will be very inconvenient. So Rust provides a convenient way to output an entire struct:
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: you must import the debug library #[derive(Debug)] , after which you can use the {:?} placeholder in the println and print macros to output an entire struct:
rect1 is Rectangle { width: 30, height: 50 }
If there are many attributes, you can use another placeholder {:#?} .
Output result:
rect1 is Rectangle {
width: 30,
height: 50
}
Struct Methods
A method (Method) is similar to a function (Function), except that it is used to operate on struct instances.
If you have learned some object-oriented languages, you surely know that functions are generally placed inside class definitions and use this in the function to represent the operated-on instance.
The Rust language is not object-oriented, as can be seen from the innovation of its ownership mechanism. But the precious ideas of object orientation can be implemented in Rust.
The first parameter of a struct method must be &self; no type needs to be declared, because self is 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 when calling a struct method you do not need to fill in self, for the sake of convenience.
An example with 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 whether rect1 is wider than rect2.
Struct Associated Functions
The reason "struct method" is not called "struct function" is that the name "function" is reserved for this kind of function: it is in an impl block but has no &self parameter.
Such a function does not depend on an instance, but to use it you need to declare which impl block it is in.
The String::from function we have been using is an "associated 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:** A struct impl block can be written several times, and the effect is equivalent to concatenating their contents!
Unit Structs
A struct can serve merely as a symbol without any members:
struct UnitStruct;
We call this kind of struct without a body a unit struct (Unit Struct).