【问题标题】:What is {} in assignment?作业中的 {} 是什么?
【发布时间】:2020-04-13 17:09:18
【问题描述】:

在 Go 中,当为数组分配多个值时,会使用大括号 {....}。这是什么牙套?是匿名结构吗?

package main

import "fmt"

func main() {
    var string_array [4]string = [4]string {"X", "Y", "Z", "W"}
    var int_array [5]int = [5]int {1,2,3}

    fmt.Println(string_array)
    fmt.Println(int_array)
}

{"X", "Y", "Z", "W"} 和下面一样,Go 运行时在做隐式转换?

    type anonymous struct {
        _0 string
        _1 string
        _2 string
        _3 string
    }
    var anon anonymous = anonymous{"X", "Y", "Z", "W"}

如果是数组,为什么不使用["X", "Y", "Z", "W"]

Golang specification 在哪里解释了这个语法?

【问题讨论】:

标签: go


【解决方案1】:

它记录在“Composite literals”下的the Go language specification(强调我的):

复合文字为结构、数组、切片和映射构造值,并在每次评估它们时创建一个新值。它们由文字类型后跟大括号绑定的元素列表组成。每个元素前面都可以有一个相应的键。

“大括号绑定”是指根据您发布的代码用{} 分隔的值。

来自语法规范:

CompositeLit  = LiteralType LiteralValue .
LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
                SliceType | MapType | TypeName .
LiteralValue  = "{" [ ElementList [ "," ] ] "}" .        <-- This production-rule, right here
ElementList   = KeyedElement { "," KeyedElement } .
KeyedElement  = [ Key ":" ] Element .
Key           = FieldName | Expression | LiteralValue .
FieldName     = identifier .
Element       = Expression | LiteralValue .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-12
    • 2017-11-29
    • 2020-07-08
    • 2018-03-17
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多