3-1
自定义类型
Rust 自定义数据类型主要是通过下面这两个关键字来创建:
struct: 定义一个结构体(structure)
enum: 定义一个枚举类型(enumeration)
而常量(constant)可以通过 const 和 static 关键字来创建。
结构体
#[derive(Debug)]
struct Person {
name: String,
age: u8,
}
struct Unit;
struct Pair(i32, f32);
struct Point {
x: f32,
y: f32,
}
#[allow(dead_code)]
struct Rectangle {
top_left: Point,
bottom_right: Point,
}
fn main() {
let name = String::from("Peter");
let age = 27;
let peter = Person { name, age };
println!("{:?}", peter);
let point: Point = Point { x: 10.3, y: 0.4 };
println!("point coordinates: ({}, {})", point.x, point.y);
let bottom_right = Point { x: 5.2, ..point };
println!("second point: ({}, {})", bottom_right.x, bottom_right.y);
let Point { x: left_edge, y: top_edge } = point;
let _rectangle = Rectangle {
top_left: Point { x: left_edge, y: top_edge },
bottom_right: bottom_right,
};
let _unit = Unit;
let pair = Pair(1, 0.1);
println!("pair contains {:?} and {:?}", pair.0, pair.1);
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
}
要点1 : 元组结构体 单元结构体
要点2 : 结构体解构
要点3 : 结构体点字段访问法 元组结构体 与 元组访问法一样
要点4 : 在声明语法中 ..结构体 可以继承其他可以继承的字段内容
struct Point {
x: f32,
y: f32,
}
struct Rectangle {
top_left: Point,
bottom_right: Point,
}
fn rect_area(rect: Rectangle) -> f32 {
let Rectangle {
top_left: Point { x: x1, y: y1 },
bottom_right: Point { x: x2, y: y2 },
} = rect;
let width = (x2 - x1).abs();
let height = (y2 - y1).abs();
width * height
}
struct Point {
x: f32,
y: f32,
}
struct Rectangle {
top_left: Point,
bottom_right: Point,
}
fn square(top_left: Point, side_length: f32) -> Rectangle {
Rectangle {
top_left: Point {
x: top_left.x,
y: top_left.y,
},
bottom_right: Point {
x: top_left.x + side_length,
y: top_left.y + side_length,
},
}
}