The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
miencun

嵌套自身的 Struct 该如何实例化?

  •  
  •   miencun · Nov 17, 2020 · 2919 views
    This topic created in 2187 days ago, the information mentioned may be changed or developed.

    有个

    type A struct { B struct { Count int json:"count" Status int json:"status" } json:"b" }

    用 A{B{Count: 112,Status: 112}}报我没有定义 B 请教请教,查了一天资料还没搞定。

    10 replies  •  2020-11-27 18:01:31 +08:00
    miencun
    miencun
    OP
    Nov 17, 2020
    1
    对了,我不想用
    var a A
    a.B.Count = 1
    a.B.Status = 2
    这种直接赋值的方法
    yrj
    yrj
    Nov 17, 2020 via iPad
    2
    那就 type 一个 b 呗。
    type b struct……
    gy0624ww
    gy0624ww
    Nov 17, 2020
    3
    type B struct {
    Count int `json:"count"`
    Status int `json:"status"`
    }
    type A struct {
    B `json:"B"`
    }

    func main() {
    a := A{B{
    Count: 11,
    Status: 10,
    }}
    fmt.Println(a)
    }
    miencun
    miencun
    OP
    Nov 17, 2020
    4
    两位老哥。 @yrj @gy0624ww

    我要嵌套自身 Struct,因为需要输出的 json 很复杂,嵌套自身这样看起来很爽
    zealic
    zealic
    Nov 17, 2020❤️1
    5
    ```go
    type A struct {
    B struct {
    Count int `json:"count"`
    Status int `json:"status"`
    } `json:"b"`
    }

    _ := A{
    B: struct {
    Count int `json:"count"`
    Status int `json:"status"`
    } {Count: 1, Status: 2},
    }
    ```

    这个玩法并不好,反而更繁琐,如要保持类型的反射匿名可以用 type def


    ```go
    type X = struct {
    Count int `json:"count"`
    Status int `json:"status"`
    }
    ```
    keepeye
    keepeye
    Nov 17, 2020
    6
    只能拆出来定义
    Adriel
    Adriel
    Nov 17, 2020 via iPhone
    7
    我杀我自己?
    index90
    index90
    Nov 17, 2020
    8
    A{B: struct {
    Count int `json:"count"`
    Status int `json:"status"`
    }{Count: 1, Status: 2}}

    B 不是类型名,是字段名
    type A 里面的 struct 是一个匿名类型
    实例化的时候,需要签名一致,tag 部分也要一样
    miencun
    miencun
    OP
    Nov 17, 2020
    9
    @index90 这就很繁琐了啊,相当于“重新定义”一次,如果这样的话,我直接用设置 B 为匿名就行了。
    sunshinev
    sunshinev
    Nov 27, 2020
    10
    为啥总是有些奇奇怪怪的用法
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2485 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 10:37 · PVG 18:37 · LAX 02:37 · JFK 05:37
    ♥ Do have faith in what you're doing.