跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • 嵌套自身的 Struct 该如何实例化?
未分類
25 11 月 2020

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

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

資深大佬 : miencun 4

有个

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

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

大佬有話說 (9)

  • 主 資深大佬 : miencun

    对了,我不想用
    var a A
    a.B.Count = 1
    a.B.Status = 2
    这种直接赋值的方法

  • 資深大佬 : yrj

    那就 type 一个 b 呗。
    type b struct……

  • 資深大佬 : gy0624ww

    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

    两位老哥。 @yrj @gy0624ww

    我要嵌套自身 Struct,因为需要输出的 json 很复杂,嵌套自身这样看起来很爽

  • 資深大佬 : zealic

    “`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

    只能拆出来定义

  • 資深大佬 : airplayxcom

    我杀我自己?

  • 資深大佬 : index90

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

    B 不是类型名,是字段名
    type A 里面的 struct 是一个匿名类型
    实例化的时候,需要签名一致,tag 部分也要一样

  • 主 資深大佬 : miencun

    @index90 这就很繁琐了啊,相当于“重新定义”一次,如果这样的话,我直接用设置 B 为匿名就行了。

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具