【问题标题】:One-liner for creating struct with blank fields?使用空白字段创建结构的单线?
【发布时间】:2015-02-18 06:06:49
【问题描述】:

我有一个带有空白字段的结构:

type Foo struct {
    a uint32
    b uint32
    c uint32
    _ uint32 //padding
}

对于没有空白字段的结构,我喜欢使用单行初始化。但是,对于带有 空白字段的类型,我似乎无法做到这一点:

Foo{1,2,3}   // too few values in struct initializer
Foo{1,2,3,0} // cannot refer to blank field or method
Foo{1,2,3,_} // cannot use _ as value

为了保持良好的语法,我必须命名未使用的字段吗?

【问题讨论】:

    标签: go


    【解决方案1】:

    您可以指定字段

    f := Foo{a: 1, b: 2, c: 3}
    fmt.Println(f) //{1 2 3 0}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 2010-10-05
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多