数组复制是深拷贝还是浅拷贝?

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

GO - Is array copy a deep copy or shallow copy?

问题

对于下面的数组,

var a[2][3]int
a[0][0] = 55
a[0][1] = 56
a[0][2] = 57
a[1][0] = 65
a[1][1] = 66
a[1][2] = 67

执行数组复制操作后,

a[0] = a[1]

问题:

数组 a[0] 的复制是深拷贝还是浅拷贝?

复制后,a[0] 的值(3个 int)与 a[1] 的值(3个 int)是否相互独立?

英文:

For the below array,

var a[2][3]int
a[0][0] = 55
a[0][1] = 56
a[0][2] = 57
a[1][0] = 65
a[1][1] = 66
a[1][2] = 67

on performing array copy,

a[0] = a[1]

Question:

Is the array(a[0]) copy a deep copy or shallow copy?

After copy, Does a[0] have separate values(3 int's) than a[1] values(3 int's)?

答案1

得分: 3

这是一个深拷贝。在Go语言中,数组不涉及任何指针(除非它是指针数组)。每个数组类型的变量都有自己的连续内存块来存储其值。

在你的初始化代码之后,a 是这样的一个内存块(连续的6个整数):

55 56 57 65 66 67

然后在拷贝之后,它变成了这样:

65 66 67 65 66 67

这里有两个独立的值的拷贝。

(但是切片是不同的。它们包含指针,因此通常是浅拷贝。)

英文:

It is a deep copy. An array in Go doesn't involve any pointers (unless it's an array of pointers, of course). Each variable of an array type has its own contiguous block of memory holding its values.

After your initialization code, a is a block of memory like this (just 6 ints in 6 consecutive memory words):

55 56 57 65 66 67

Then after the copy, it is like this:

65 66 67 65 66 67

There are two separate copies of the values.

(But slices are different. They do have pointers, and so they are normally copied shallowly.)

huangapple
  • 本文由 发表于 2017年1月27日 12:39:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/41887050.html
匿名

发表评论

匿名网友

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

确定