// structs
struct Point {
x: i32,
y: i32,
}
let mut 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;
一个包含..的struct可以用来从其它结构体拷贝一些值或者在解构时忽略一些域:
#[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;
需要注意,Rust在语言级别不支持域可变性 (field mutability),所以不能这么写:
struct Point {
mut x: i32,
y: i32,
}
这是因为可变性是绑定的一个属性,而不是结构体自身的。可以使用Cell<T>来模拟:
use std::cell::Cell;
struct Point {
x: i32,
y: Cell<i32>,
}
let mut point = Point { x: 5, y: Cell::new(6) };
point.y.set(7);