zoukankan      html  css  js  c++  java
  • 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
    ", 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
    ", 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
    ", 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"

  • 相关阅读:
    IOS8修改状态栏颜色
    iOS文件存储路径规定
    iOS+HTML5
    调用电话/获取通讯录
    iOS高级必备
    CoreData
    IOS 中的CoreImage框架
    CoreText
    CoreGpaphics
    iOS多线程 NSThread/GCD/NSOperationQueue
  • 原文地址:https://www.cnblogs.com/neozheng/p/13167273.html
Copyright © 2011-2022 走看看