使用以下代码:
struct Point {
x: f64,
y: f64,
}
struct Rectangle {
p1: Point,
p2: Point,
}
impl Rectangle {
pub fn new(x1: f64, y1: f64, x2: f64, y2: f64) -> Rectangle {
let r = Rectangle {
p1: Point { x: x1, y: y1 },
p2: Point { x: x2, y: y2 },
};
// some code where r is used
r
}
}
let rectangle = Rectangle::new(0.0, 0.0, 10.0, 10.0);
从内存角度来看,rectangle
和r
是同一个实例还是r
的副本?
我是否必须显式返回引用(类似于&r
)?
我需要创建数百万个矩形,而我不希望有无用的副本。
drop()
来释放原始值的资源? - Ilya LoskutovClone
和Copy
。当您创建一个clone
时,(用户)指定了创建克隆所涉及的逻辑;例如,对于String
,这意味着分配第二个缓冲区并将第一个缓冲区的内容复制到其中。克隆后,两个实例将独立地生活。如果您不需要键入.clone()
,则Rust只是_移动_实例。如果实例已经被移动,则它不会被丢弃。如果实例被复制(Copy
),则删除是无操作的。 - Matthieu M.Copy
)时,永远不会调用Drop
。 - Matthieu M.