gpt4 book ai didi

arrays - 如何在不更改原始数组的情况下复制数组?

转载 作者:行者123 更新时间:2023-12-03 22:48:20 24 4
gpt4 key购买 nike

我想复制一个数组,但复制的数组也总是对原始数组进行更改。为什么会这样?
以下是该问题的代码示例:

package main

import (
"fmt"
)

func main() {
array := make([]int, 2)
for i := range array {
array[i] = 0
}

oldArray := array
array[0] = 3 // why does this also change oldArray?
oldArray[1] = 2 // why does this also change the original array?

fmt.Println(oldArray, array)
// I expected [0,2], [3,0]
// but it returns [3,2], [3,2]

}
我试图启动变量 oldArray之前 array但结果是一样的。

最佳答案

在您的示例代码中,您正在使用 slices ,不是 arrays .
从 slice 文档:

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array.


当您将 slice 分配给变量时,您正在创建该描述符的副本,因此处理相同的底层数组。当您实际使用数组时,它具有您期望的行为。
slice 文档中的另一个片段(重点是我的):

A slice, once initialized, is always associated with an underlying array that holds its elements. A slice therefore shares storage with its array and with other slices of the same array; by contrast, distinct arrays always represent distinct storage.


这是一个代码示例(对于 slice ,第一个元素的内存地址在括号中,以明确指出两个 slice 何时使用相同的底层数组):
package main

import (
"fmt"
)

func main() {
// Arrays
var array [2]int
newArray := array
array[0] = 3
newArray[1] = 2
fmt.Printf("Arrays:\narray: %v\nnewArray: %v\n\n", array, newArray)

// Slices (using copy())
slice := make([]int, 2)
newSlice := make([]int, len(slice))
copy(newSlice, slice)
slice[0] = 3
newSlice[1] = 2
fmt.Printf("Slices (different arrays):\nslice (%p): %v \nnewSlice (%p): %v\n\n", slice, slice, newSlice, newSlice)

// Slices (same underlying array)
slice2 := make([]int, 2)
newSlice2 := slice2
slice2[0] = 3
newSlice2[1] = 2
fmt.Printf("Slices (same array):\nslice2 (%p): %v \nnewSlice2 (%p): %v\n\n", slice2, slice2, newSlice2, newSlice2)
}
输出:
Arrays:
array: [3 0]
newArray: [0 2]

Slices (different arrays):
slice (0xc000100040): [3 0]
newSlice (0xc000100050): [0 2]

Slices (same array):
slice2 (0xc000100080): [3 2]
newSlice2 (0xc000100080): [3 2]
Go Playground

关于arrays - 如何在不更改原始数组的情况下复制数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66576981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com