gpt4 book ai didi

arrays - Go语言复制数组的函数

转载 作者:IT老高 更新时间:2023-10-28 13:03:42 26 4
gpt4 key购买 nike

Go 中是否有任何内置函数可以将一个数组复制到另一个数组?这适用于二维(或更多)维数组吗?

最佳答案

Is there any built-in function in Go language for copying one array to another?

是的:http://play.golang.org/p/_lYNw9SXN5

a := []string{
"hello",
"world",
}
b := []string{
"goodbye",
"world",
}

copy(a, b)

// a == []string{"goodbye", "world"}

Will this work in case of two (or more) dimensional arrays?

copy 将对行进行浅拷贝:http://play.golang.org/p/0gPk6P1VWh

a := make([][]string, 10)

b := make([][]string, 10)
for i := range b {
b[i] = make([]string, 10)
for j := range b[i] {
b[i][j] = strconv.Itoa(i + j)
}
}

copy(a, b)

// a and b look the same

b[1] = []string{"some", "new", "data"}

// b's second row is different; a still looks the same

b[0][0] = "apple"

// now a looks different

我不认为有用于执行多维数组深拷贝的内置程序:您可以手动执行,例如:http://play.golang.org/p/nlVJq-ehzC

a := make([][]string, 10)

b := make([][]string, 10)
for i := range b {
b[i] = make([]string, 10)
for j := range b[i] {
b[i][j] = strconv.Itoa(i + j)
}
}

// manual deep copy
for i := range b {
a[i] = make([]string, len(b[i]))
copy(a[i], b[i])
}

b[0][0] = "apple"

// a still looks the same

edit:正如评论中所指出的,我假设“复制数组”是指“对 slice 进行深度复制”,因为数组可以使用 = 运算符进行深度复制根据 jnml 的回答(因为数组是值类型):http://play.golang.org/p/8EuFqXnqPB

关于arrays - Go语言复制数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18559830/

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