切片中的数组

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

Array within a slice

问题

在Go语言中,可以在切片中放置一个数组。你可以使用以下语法来定义一个切片,其中包含一个具有2个元素的不可变数组:[][2]int。要创建一个实例,你可以使用切片字面量的方式,例如[][]int{{1, 2}, {3, 4}}。这将创建一个包含两个元素的切片,每个元素都是一个具有两个整数的数组。与Python中的表示方式类似。

英文:

is it possible to put a array within a slice? I tried [][2]int, but I can't figure out how to create an instance. The end result should be a mutable slice around an immutable 2 item array.

In python it would look like: [(1,2),(3,4)].

答案1

得分: 2

Go语法使用{}大括号表示切片(slices)和数组(arrays)。

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

但是当可以推断出内部类型时,你可以省略字面量中的内部类型:

s := [][2]int{{1, 2}, {3, 4}}
s = append(s, [2]int{5, 6})
英文:

Go syntax uses {} braces for slices and arrays.

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

But you can elide the inner types in the literal when they can be inferred:

s := [][2]int{{1, 2}, {3, 4}}
s = append(s, [2]int{5, 6})

huangapple
  • 本文由 发表于 2017年3月11日 05:02:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/42727670.html
匿名

发表评论

匿名网友

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

确定