Structs in Rust

environment

  • windows 10 64bit

Introduction

A structure in Rust is a custom data type that can combine values ​​of multiple different data types to meet the actual needs of the project.

definition

Rust uses the keyword struct to define and name structures

 struct User { name: String, age: u32, score: f64, married: bool, }

The curly brackets are the various types of data contained in the structure, including the name and type, and these data are the fields of the structure.

Now that the structure is defined, let’s see how to create a structure instance

 let user_jack = User { name: String::from("jack"), age: 20, score: 100.0, married: false, };

The order of each field is irrelevant, the name and married positions can be interchanged, and the dot operation is used to refer to the fields in the structure instance

 // 获取name字段值user.jack.name // 获取married字段值user.jack.married

Like ordinary data types, by default, structure instances are immutable. To make them mutable, add the mut keyword. If the instance is mutable, then all fields of the instance are mutable.

 let mut user_jack = User { name: String::from("jack"), age: 20, score: 100.0, married: false, }; user_jack.score = 95.5;

In addition to the above methods, you can also use another way similar to tuples to define structures, which are also called tuple structures

 struct RGB(i32, i32, i32); let black = RGB(0, 0, 0);

It can be seen that the tuple structure does not need to name each field, only the data type of the field is given

This article is transferred from https://xugaoxiang.com/2023/02/06/rust-struct/
This site is only for collection, and the copyright belongs to the original author.