英文:
Does the .clone() method always make a deep copy?
问题
- 我的理解正确吗?
- 如果不是,有哪些情况下这个方法不会创建一个对象的“深度”拷贝?
英文:
While reading through a few of the Rust docs, I came across the following;
> ... use .clone()
to explicitly copy the data.
The choice of "copy" here kind of puzzled me, specifically whether I can always replace "copy" with "deep copy" and for the statement to always hold true.
To my understanding, the Clone
trait indicates the possibility of either a shallow or deep copy of the data type implementing it, but the explicit use of .clone()
method will create a deep copy.
- Is my understanding correct?
- If not, what are some examples the method does not create a "deep" copy of an object?
答案1
得分: 0
没有。虽然Clone
可以是浅复制(例如Rc
)或深复制(例如Box
),但它总是通过调用.clone()
来触发的,所以.clone()
也可以创建浅复制(取决于类型)。
英文:
> Is my understanding correct?
No. It is true that Clone
can be either shallow (e.g. Rc
) or deep (e.g. Box
) copy, but it is always triggered by calling .clone()
, so .clone()
can make a shallow copy too (depending on the type).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论