为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 reflect in go 从结构子字段中获取项目数

如何使用 reflect in go 从结构子字段中获取项目数

婷婷同学_ 2023-02-06 10:35:13
reflect通过包从切片结构中的子字段获取项目数时,我遇到了一些问题。这就是我试图从中获取项目数量的方式Itemsfunc main() {  type Items struct {      Name    string `json:"name"`      Present bool   `json:"present"`  }  type someStuff struct {      Fields string     `json:"fields"`      Items    []Items `json:"items"`  }  type Stuff struct {      Stuff []someStuff `json:"stuff"`  }  some_stuff := `{                  "stuff": [                     {                       "fields": "example",                       "items": [                         { "name": "book01", "present": true },                         { "name": "book02", "present": true },                         { "name": "book03", "present": true }                                                               ]                     }                   ]                }`  var variable Stuff  err := json.Unmarshal([]byte(some_stuff), &variable)  if err != nil {      panic(err)  }  //I want to get the number of items in my case 3  NumItems := reflect.ValueOf(variable.Stuff.Items)}这是错误:variable.Items undefined (type []Stuff has no field or method Items)我不确定我是否可以检索到这样的项目数量。
查看完整描述

1 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

我已经解决了这个问题。


为了获得子字段的数量,我们可以使用Len()from reflect.ValueOf。


现在的代码正在获取项目的数量:


package main


import (

    "encoding/json"

    "fmt"

    "reflect"

)


func main() {


    type Items struct {

        Name    string `json:"name"`

        Present bool   `json:"present"`

    }


    type someStuff struct {

        Fields string  `json:"fields"`

        Items  []Items `json:"items"`

    }


    type Stuff struct {

        Stuff []someStuff `json:"stuff"`

    }


    some_stuff := `{

                  "stuff": [

                     {

                       "fields": "example",

                       "items": [

                         { "name": "book01", "present": true },

                         { "name": "book02", "present": true },

                         { "name": "book03", "present": true }                                        

                       ]

                     }

                   ]

                }`


    var variable Stuff


    err := json.Unmarshal([]byte(some_stuff), &variable)

    if err != nil {

        panic(err)

    }


    //I want to get the number of items in my case 3

    t := reflect.ValueOf(variable.Stuff[0].Items)

    fmt.Println(t.Len())


}


Output: 3


查看完整回答
反对 回复 2023-02-06
  • 1 回答
  • 0 关注
  • 84 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信