2

Rust 中的结构体 - 迷途小书童的Note迷途小书童的Note

 1 year ago
source link: https://xugaoxiang.com/2023/02/06/rust-struct/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
  • windows 10 64bit

Rust 中的结构体是一种自定义的数据类型,它可以将多个不同数据类型的值组合起来,满足项目中的实际需求。

Rust 使用关键字 struct 来定义并命名结构体

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

大括号中是结构体所包含的各类型数据,包括名称和类型,这些数据是结构体的各个字段。

定义好了结构体,下面看看如何创建结构体实例

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

各个字段的顺序是无关的,完全可以将 namemarried 位置互换,使用点操作来引用结构体实例中的字段

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

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

与普通的数据类型一样,默认情况下,结构体实例是不可变的,要使其可变,就要加上 mut 关键字。如果实例是可变的,那么实例的所有字段都是可变的。

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

user_jack.score = 95.5;

除了上面的方法,还可以使用另外一种类似于元组的方式定义结构体,这种结构体也叫元组结构体

struct RGB(i32, i32, i32);

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

可以看到,元组结构体不需要对各个字段进行命名,仅仅给出了字段的数据类型


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK