Golang :索引值对的数组

The literal syntax is similar for arrays, slices, maps, and structs (数组、slice、map和结构体字面值的写法都很相似). The common form of arrays is a list of values in order, but it is also possible to specify a list of index and value pairs, like below:

package main

import (
    "fmt"
)

func main() {
    type Currency int
    const (
        USD Currency = iota
        EUR
        GBP
        RMB
    )
    symbol := [...]string{EUR: "", RMB: "¥", GBP: "£", USD: "$"} // 索引-值 对形式的数组
    for i, v := range symbol {
        fmt.Printf("i:%v | v:%v\n", i, v)
    }
}

/*
运行结果:
MacBook-Pro:unspecified_val zhenxink$ go run unspecified_val_array.go
i:0 | v:$
i:1 | v:€
i:2 | v:£
i:3 | v:¥
*/

In this form, indices can appear in any order and some may be omitted; as before, unspecified values take on the zero value for the element type. For instance,

r := [...]int{9: -1}    // it defines any array r with 100 elements, all zero except for the last ,which has value -1 

示例一:

package main

import (
    "fmt"
)

func main() {
    r := [...]int{9: -1}
    for i, v := range r {
        fmt.Printf("i:%v | v:%v\n", i, v)
    }
}


/* 运行结果:
MacBook-Pro:unspecified_val zhenxink$ go run unspecified_val_array.go 
i:0 | v:0
i:1 | v:0
i:2 | v:0
i:3 | v:0
i:4 | v:0
i:5 | v:0
i:6 | v:0
i:7 | v:0
i:8 | v:0
i:9 | v:-1
*/

示例二:

package main

import (
    "fmt"
)

func main() {
    r := [...]int{9: 2, -1}    // 9表示从0开始最后的索引值为9,即长度为10
    for i, v := range r {
        fmt.Printf("i:%v | v:%v\n", i, v)
    }
}


/* 运行结果:
MacBook-Pro:unspecified_val zhenxink$ go run unspecified_val_array.go 
i:0 | v:0
i:1 | v:0
i:2 | v:0
i:3 | v:0
i:4 | v:0
i:5 | v:0
i:6 | v:0
i:7 | v:0
i:8 | v:0
i:9 | v:2
i:10 | v:-1
*/

-- Excerpt from "The Go Programming Language"

猜你喜欢

转载自www.cnblogs.com/neozheng/p/13167273.html