# 结构体

structs.md

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; // now immutable

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

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

struct PointRef<'a> {
x: &'a mut i32,
y: &'a mut i32,
}

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

{
let r = PointRef { x: &mut point.x, y: &mut point.y };

*r.x = 5;
*r.y = 6;
}

assert_eq!(5, point.x);
assert_eq!(6, point.y);
}

## 更新语法（Update syntax）

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

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

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

## 元组结构体

Rust有像另一个[元组](Primitive Types 原生类型.md#tuples)和结构体的混合体的数据类型。元组结构体有一个名字，不过它的字段没有。他们用struct关键字声明，并元组前面带有一个名字：

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

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

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 structs）

struct Electron;

let x = Electron;