.clone() 方法始终创建深拷贝吗?

huangapple go评论51阅读模式
英文:

Does the .clone() method always make a deep copy?

问题

  1. 我的理解正确吗?
  2. 如果不是,有哪些情况下这个方法不会创建一个对象的“深度”拷贝?
英文:

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.

  1. Is my understanding correct?
  2. 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).

huangapple
  • 本文由 发表于 2023年6月5日 11:37:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403372.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定