struct Point {
x: i32,
y: i32,
}
struct Rectangle {
top_left: Point,
bottom_right: Point,
}
fn main() {
let point1 = Point { x: 0, y: 0 };
let point2 = Point { x: 10, y: 10 };
let rect = Rectangle {
top_left: point1,
bottom_right: point2,
};
// 此时point1和point2的所有权已经转移到rect中,不能再使用point1和point2
// println!("{:?}", point1); // 这行代码会报错
}
内存管理解释
Point
实例的创建:当let point1 = Point { x: 0, y: 0 };
和let point2 = Point { x: 10, y: 10 };
执行时,在栈上为point1
和point2
分配空间,它们各自包含两个i32
类型的字段x
和y
,这些i32
值也直接存储在栈上。
Rectangle
实例的创建:当let rect = Rectangle { top_left: point1, bottom_right: point2, };
执行时,point1
和point2
的所有权被转移到rect
中。rect
在栈上分配空间,其top_left
和bottom_right
字段直接存储Point
实例,由于Point
实例较小,其所有数据(x
和y
)也在栈上。
- 作用域结束:当
main
函数结束时,rect
离开作用域,rect
占用的栈空间被释放,同时其内部的top_left
和bottom_right
(即原来的point1
和point2
)占用的栈空间也随之释放。