What does `shallow clone` mean?

212 views
Skip to first unread message

Shinya Sakae

unread,
Aug 11, 2023, 12:56:01 PM8/11/23
to golang-nuts
maps package was released with Go 1.21.
Clone() comment says "This is a shallow clone".
I often hear the term `shallow copy', but I don't know what `shallow clone` means.
What is the state of a `shallow cloned` map?
Do you mean that the cloned map values are shallow copied?

> Clone returns a copy of m. This is a shallow clone: the new keys and values are set using ordinary assignment.

https://pkg.go.dev/maps@master#Clone

Brian Candler

unread,
Aug 14, 2023, 3:11:56 AM8/14/23
to golang-nuts
On Friday, 11 August 2023 at 17:56:01 UTC+1 Shinya Sakae wrote:
I often hear the term `shallow copy', but I don't know what `shallow clone` means.

Don't worry: they are the same thing.

When cloning a map, the keys and values are set using ordinary assignment, as the description says.  It means there is no recursive cloning of nested structures.

For example: assignment of a map ends up with two values pointing at the *same* data structure:
(that's why clone is needed in the first place: so you can add/update/delete to the clone, without affecting the source map)

Therefore, if you have an outer map containing inner maps as values, and you clone the outer map, the clone will still refer to the same inner maps.

Shinya Sakae

unread,
Aug 15, 2023, 9:52:38 AM8/15/23
to golang-nuts
Hi Brian.
Thanks for reaching out.
I understand.

Reply all
Reply to author
Forward
0 new messages