结构体

2018-08-12 22:03 更新

结构体

``````let origin_x = 0;
let origin_y = 0;``````

``````struct Point {
x: i32,
y: i32,
}

fn main() {
let origin = Point { x: 0, y: 0 }; // origin: Point

println!("The origin is at ({}, {})", origin.x, origin.y);
}``````

``````struct Point {
x: i32,
y: i32,
}

fn main() {
let mut point = Point { x: 0, y: 0 };

point.x = 5;

println!("The point is at ({}, {})", point.x, point.y);
}``````

Rust 在语言层面不支持字段可变性，所以你不能像以下这样书写代码：

``````struct Point {
mut x: i32,
y: i32,
}``````

``````struct Point {
x: i32,
y: i32,
}

fn main() {
let mut point = Point { x: 0, y: 0 };

point.x = 5;

let point = point; // this new binding can’t change now

point.y = 6; // this causes an error
}``````

语法更新

``````struct Point3d {
x: i32,
y: i32,
z: i32,
}

let mut point = Point3d { x: 0, y: 0, z: 0 };
point = Point3d { y: 1, .. point };``````

``````let origin = Point3d { x: 0, y: 0, z: 0 };
let point = Point3d { z: 1, x: 2, .. origin };``````

数组结构体

Rust 有另外一个数据类型就像一个数组与一个结构体的混合，称为“数组结构体”。数组结构体有一个名字，但是它们的字段没有名字：

``````struct Color(i32, i32, i32);
struct Point(i32, i32, i32);``````

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

``````struct Color {
red: i32,
blue: i32,
green: i32,
}

struct Point {
x: i32,
y: i32,
z: i32,
}``````

``````struct Inches(i32);

let length = Inches(10);

let Inches(integer_length) = length;
println!("length is {} inches", integer_length);``````

Unit-like 结构体

``struct Electron;``

App下载