如何增加数组大小

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

How to increase array size

问题

假设我有一个数组:

array1 := [5]int {
    1,2,3,4,5,
}

我需要增加这个数组的大小。

  • 在Go语言中,如何增加数组的大小以便添加额外的元素?

如果我有另一个数组:

array2 := [5]int {
    6,7,8,9,10,
}
  • 如何将array2追加到array1

然后array1将打印出[1,10]

for i:=0; i<len(array1); i++ {
    fmt.Print(array1[i], ",")
}

输出:

1,2,3,4,5,6,7,8,9,10
英文:

Suppose I have an array

array1 := [5]int {
    1,2,3,4,5,
}

And I need to increase this array size.

  • How can I increase array size in go so that I can add additional element?

If I have another array

array2 := [5]int {
    6,7,8,9,10,
}
  • How can I append array2 with array1?

Then array1 will print [1,10]

for i:=0; i&lt;len(array1); i++ {
	fmt.Print(array1[i], &quot;,&quot; )
}

Output:

1,2,3,4,5,6,7,8,9,10

答案1

得分: 12

唯一改变数组大小的方法是创建一个新数组。你可以使用切片(slice),它的行为类似于数组,但可以动态调整大小。你可以使用append方法向切片中添加元素。

slice1 := []int{1,2,3,4,5}
slice2 := []int{6,7,8,9,10}
slice1 = append(slice1, slice2...)
for v, _ := range slice1 {
   fmt.Println(v)
}

以上代码将把slice2中的元素追加到slice1中,并打印出slice1中的每个元素。

英文:

The only way to 'resize' an array is to make a new one. You can use a slice which behaves much like an array, but is resized dynamically for you. You use the append method to add items to a slice.

slice1 := []int{1,2,3,4,5}
slice2 := []int{6,7,8,9,10}
slice1 = append(slice1, slice2...)
for v, _ := range slice1 {
   fmt.Println(v)
}

huangapple
  • 本文由 发表于 2015年9月4日 00:34:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/32381079.html
匿名

发表评论

匿名网友

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

确定