猿问

关于 golang 数组

a := [...]int{5, 4: 1, 0, 2: 3, 2, 1: 4 }

fmt.Println(a)

结果是 [5 4 3 2 1 0]。怎么排序?


a := [...]int{5, 4: 1, 0, 2: 3, 2, 1: 4 ,12,11,10}

fmt.Println(a)

结果是


prog.go:8: duplicate index in array literal: 2

prog.go:8: duplicate index in array literal: 3

prog.go:8: duplicate index in array literal: 4

 [process exited with non-zero status]

谁能解释这两个结果?


牧羊人nacy
浏览 182回答 2
2回答

紫衣仙女

前几天我看到戴夫切尼推特了。我的理解是这样的:第一个 - 戴夫的工作的<number_here>:是阵列中的索引。这“设置”了当前索引......这就是为什么进一步进入声明索引必须“重置”回到数组中。因此,第一个数字是5(索引 0),第二个“条目”的索引为4:.. 因此该值1将位于索引 4:5 _ _ _ 1 _&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;^ index is currently here..下一个没有索引,但它会在给定的最后一个索引之后继续。这是4+1.. 所以 index5获取值0:5 _ _ _ 1 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;^ index is here.. it needs to be reset现在索引将溢出.. 所以它会被设置得更远。下一个是2:.. 以便将值放在下面的值中3:5 _ 3 _ 1 0&nbsp; &nbsp; &nbsp;^ index is here再下一个,继续,因为它没有索引:5 _ 3 2 1 0&nbsp; &nbsp; &nbsp; &nbsp;^ index is here然后最后一个索引1:.. 值为 4:5 4 3 2 1 0第二个——你坏掉的那个。第二个是同样的事情 - 但你没有保护当前放置的索引的覆盖。让我们一步一步来:值5在索引0:5 _ _ _ _ _ _ _ _&nbsp;^ index is here值1在索引4:5 _ _ _ 1 _ _ _ _&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;^ index is here值0在指数5(请记住,它仍在继续):5 _ _ _ 1 0 _ _ _&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;^ index is here值3在索引2:5 _ 3 _ 1 0 _ _ _&nbsp; &nbsp; &nbsp;^ index is here值2在指数3(再次,它仍在继续:5 _ 3 2 1 0 _ _ _&nbsp; &nbsp; &nbsp; &nbsp;^ index is here值4在索引1:5 4 3 2 1 0 _ _ _&nbsp; &nbsp;^ index is here ... you're awfully close to overwriting the next value值12在索引2:5 4 12 2 1 0 _ _ _&nbsp; &nbsp; ^^^^^ BOOOM繁荣....你已经覆盖了值 3 并将继续这样做,因为索引是用于剩余值的。这就是问题..

白衣染霜花

复合文字复合文字为结构体、数组、切片和映射构造值,并在每次评估它们时创建一个新值。它们由值的类型后跟花括号绑定的复合元素列表组成。元素可以是单个表达式或键值对。艾塔在常量声明中,预先声明的标识符 iota 表示连续的无类型整数常量。每当保留字 const 出现在源中并在每个 ConstSpec 之后递增时,它就会重置为 0。可以用来构造一组相关的常量例如,使用基于 iota 的密钥,以下是等效的,package mainimport "fmt"func main() {&nbsp; &nbsp; a := [...]int{5, 4: 1, 0, 2: 3, 2, 1: 4}&nbsp; &nbsp; fmt.Println(a)&nbsp; &nbsp; b := [...]int{0: 5, 4: 1, 5: 0, 2: 3, 3: 2, 1: 4}&nbsp; &nbsp; fmt.Println(b)&nbsp; &nbsp; c := make([]int, 6)&nbsp; &nbsp; i := 0&nbsp; &nbsp; c[i] = 5&nbsp; &nbsp; i = 4&nbsp; &nbsp; c[i] = 1&nbsp; &nbsp; i++&nbsp; &nbsp; c[i] = 0&nbsp; &nbsp; i = 2&nbsp; &nbsp; c[i] = 3&nbsp; &nbsp; i++&nbsp; &nbsp; c[i] = 2&nbsp; &nbsp; i = 1&nbsp; &nbsp; c[i] = 4&nbsp; &nbsp; fmt.Println(c)}输出:[5 4 3 2 1 0][5 4 3 2 1 0][5 4 3 2 1 0]冲突会导致错误,例如,a隐式和b显式,package mainimport "fmt"func main() {&nbsp; &nbsp; a := [...]int{5, 4: 1, 0, 2: 3, 2, 1: 4, 12, 11, 10}&nbsp; &nbsp; fmt.Println(a)&nbsp; &nbsp; b := [...]int{0: 5, 4: 1, 5: 0, 2: 3, 3: 2, 1: 4, 2: 12, 3: 11, 4: 10}&nbsp; &nbsp; fmt.Println(b)}输出:prog.go:6: duplicate index in array literal: 2prog.go:6: duplicate index in array literal: 3prog.go:6: duplicate index in array literal: 4prog.go:8: duplicate index in array literal: 2prog.go:8: duplicate index in array literal: 3prog.go:8: duplicate index in array literal: 4
随时随地看视频慕课网APP

相关分类

Go
我要回答