# 箱子、栈和堆

``````use std::mem;

#[derive(Debug, Clone, Copy)]
struct Point {
x: f64,
y: f64,
}

struct Rectangle {
p1: Point,
p2: Point,
}

fn origin() -> Point {
Point { x: 0.0, y: 0.0 }
}

fn boxed_origin() -> Box<Point> {
// 在堆上分配这个点（point），并返回一个指向它的指针
Box::new(Point { x: 0.0, y: 0.0 })
}

fn main() {
// （所有的类型标注都不是必需的）
// 栈分配的变量
let point: Point = origin();
let rectangle: Rectangle = Rectangle {
p1: origin(),
p2: Point { x: 3.0, y: 4.0 }
};

// 堆分配的 rectangle（矩形）
let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle {
p1: origin(),
p2: origin()
});

// 函数的输出可以装箱
let boxed_point: Box<Point> = Box::new(origin());

// 两层装箱
let box_in_a_box: Box<Box<Point>> = Box::new(boxed_origin());

println!("Point occupies {} bytes in the stack",
mem::size_of_val(&point));
println!("Rectangle occupies {} bytes in the stack",
mem::size_of_val(&rectangle));

// box 的宽度就是指针宽度
println!("Boxed point occupies {} bytes in the stack",
mem::size_of_val(&boxed_point));
println!("Boxed rectangle occupies {} bytes in the stack",
mem::size_of_val(&boxed_rectangle));
println!("Boxed box occupies {} bytes in the stack",
mem::size_of_val(&box_in_a_box));

// 将包含在 `boxed_point` 中的数据复制到 `unboxed_point`
let unboxed_point: Point = *boxed_point;
println!("Unboxed point occupies {} bytes in the stack",
mem::size_of_val(&unboxed_point));
}
``````