How do I initialize a composed struct in Go?

后端 未结 1 857
忘了有多久
忘了有多久 2020-12-10 01:25

Let\'s say I have a struct with another struct embedded in it.

type Base struct {
    ID string
}

type Child struct {
    Base
    a int
    b int
}
         


        
相关标签:
1条回答
  • 2020-12-10 01:51

    Go issue 9859 proposes a change the the language to support the Child{ ID: id, a: a, b: b } syntax from the question.

    Use nested composite literals to initialize a value in a single expression:

    child := Child{Base: Base{ID: id}, a: a, b: b}
    

    It is not possible to hide the fact that a field is promoted from an embedded struct.

    0 讨论(0)
提交回复
热议问题