用Go语言复制数组的功能 [英] Function for copying arrays in Go language
问题描述
Go中是否有用于将一个数组复制到另一个数组的内置函数?在二维(或更多)维数组的情况下是否可以使用?
Is there any built-in function in Go for copying one array to another? Will this work in case of two (or more) dimensional arrays?
推荐答案
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
copy
will do a shallow copy of the rows: 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
我认为没有内置的功能可以对多维数组进行深度复制:您可以手动进行操作,例如:
I don't think there's a built-in for doing deep-copys of multi-dimensional arrays: you can do it manually like: 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:正如评论中所指出的那样,我假设复制数组"的意思是进行切片的深层复制",因为可以使用 =
运算符对数组进行深层复制按照jnml的答案(因为数组是值类型): http://play.golang.org/p/8EuFqXnqPB
edit: As pointed out in the comments, I assumed by "copy an array" you meant "do a deep copy of a slice", as arrays can be deep-copied with the =
operator as per jnml's answer (because arrays are value types): http://play.golang.org/p/8EuFqXnqPB
这篇关于用Go语言复制数组的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!