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: "$"} // 索引-值 對形式的數組;index must be non-negative integer constant(數組的索引只能為非負整數)
    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"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM