# 结构体与枚举

## 结构体

// structs
struct Point {
x: i32,
y: i32,
}
let point = Point { x: 0, y: 0 };

// tuple structs
struct Color(u8, u8, u8);
let android_green = Color(0xa4, 0xc6, 0x39);
let Color(red, green, blue) = android_green;

// A tuple struct’s constructors can be used as functions.
struct Digit(i32);
let v = vec![0, 1, 2];
let d: Vec<Digit> = v.into_iter().map(Digit).collect();

// newtype: a tuple struct with only one element
struct Inches(i32);
let length = Inches(10);
let Inches(integer_length) = length;

// unit-like structs
struct EmptyStruct;
let empty = EmptyStruct;

#[derive(Default)]
struct Point3d {
x: i32,
y: i32,
z: i32,
}

let origin = Point3d::default();
let point = Point3d { y: 1, ..origin };
let Point3d { x: x0, y: y0, .. } = point;

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

use std::cell::Cell;

struct Point {
x: i32,
y: Cell<i32>,
}

let point = Point { x: 5, y: Cell::new(6) };

point.y.set(7);

mod graph {
#[derive(Default)]
pub struct Point {
pub x: i32,
y: i32,
}

pub fn inside_fn() {
let p = Point {x:1, y:2};
println!("{}, {}", p.x, p.y);
}
}

fn outside_fn() {
let p = graph::Point::default();
println!("{}", p.x);
// println!("{}", p.y);
// field y of struct graph::Point is private
}

## 枚举

Rust有一个集合类型，称为枚举 (enum)，代表一系列子数据类型的集合。 其中子数据结构可以为空-如果全部子数据结构都是空的，就等价于C语言中的enum。 我们需要使用::来获得每个元素的名称。

// enums
enum Message {
Quit,
ChangeColor(i32, i32, i32),
Move { x: i32, y: i32 },
Write(String),
}

let x: Message = Message::Move { x: 3, y: 4 };