# 結構體

let origin_x = 0;
let origin_y = 0;


struct 讓我們可以將兩者合而為一，成為一個有 xy 欄位（field）的統一資料型態：

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);
}


## 更新語法

struct 可以使用 .. 來表示你想使用其他 struct 中某些值的複本。 舉例來說：

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 };


## 多元組結構體（tuple struct）

Rust 還有其他類似多元組（tuple）與 struct 混合體的資料型別，叫做「多元組結構體」（tuple struct）。 多元組結構體本身有命名，但是它的欄位沒有。 它也使用 struct 關鍵字宣告，在其後加上名字和多元組：

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

struct Electron;

let x = Electron;


commit 6ba9520