GO-阵列副本是深层副本还是浅层副本? [英] GO - Is array copy a deep copy or shallow copy?

查看:64
本文介绍了GO-阵列副本是深层副本还是浅层副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下数组,

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] )是复制深拷贝还是浅拷贝?

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

复制后, a [0] 是否具有与 a [1] 值(3 int 's)?

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

推荐答案

它是一个深层副本.Go中的数组不涉及任何指针(当然,除非是指针数组).数组类型的每个变量都有自己的连续内存块,用于保存其值.

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.

初始化代码之后, a 是这样的内存块(在6个连续的存储字中仅6个 int s):

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.)

这篇关于GO-阵列副本是深层副本还是浅层副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆