【问题标题】:Instantiating Golang Data []struct [duplicate]实例化 Golang 数据 []struct [重复]
【发布时间】:2021-03-23 13:48:03
【问题描述】:

我对 Golang 很陌生,我正在尝试做一些我认为很容易的事情,但我在完成它时遇到了麻烦。给定以下代码

package main

import (
    "encoding/json"
    "fmt"
    "os"
)


type Example struct {
    Data []struct {
        Name                    string   `json:"Name"`
        Onboarded               bool     `json:"Onboarded"`
    } `json:"data"`
}


func main() {

    // This is what I am trying to figure out.
    // How do I properly instantiate the Example type struct with values ? 
    // I'm not getting the Data part.
    example := Example{
        Data: ...
    }
}

感谢任何帮助。谢谢。

【问题讨论】:

    标签: go struct


    【解决方案1】:

    使用匿名类型的复合文字可能非常冗长。通过声明类型来简化工作:

    type Example struct {
        Data []Employee `json:"data"`
    }
    
    type Employee struct {
        Name                    string   `json:"Name"`
        Onboarded               bool     `json:"Onboarded"`
    }
    

    以下是这些类型的复合文字:

    example := Example{
        Data: []Employee{
           {Name: "Russ C.", Onboarded: true},
           {Name: "Brad F.", Onboarded: false},
        },
    }
    

    【讨论】:

      【解决方案2】:

      我认为一个(方式)更惯用的解决方案是为嵌套结构定义一个类型。无论如何,你可以这样做:

      example := Example{
              Data: []struct {
                  Name      string `json:"Name"`
                  Onboarded bool   `json:"Onboarded"`
              }{
                  {Name: "Idk", Onboarded: false},
                  {Name: "More", Onboarded: true},
              },
          }
      

      理想情况下,您应该这样做:

      type Example struct {
          Data []ExampleNested `json:"data"`
      }
      
      type ExampleNested struct {
          Name      string `json:"Name"`
          Onboarded bool   `json:"Onboarded"`
      }
      

      然后:

      example := Example{
              Data: []ExampleNested{
                  {Name: "Idk", Onboarded: false},
                  {Name: "More", Onboarded: false},
              },
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        • 2021-02-11
        • 1970-01-01
        相关资源
        最近更新 更多