登录
首页 >  Golang >  Go问答

在Go语言中,如何利用反射从结构体子字段中获取字段数

来源:stackoverflow

时间:2024-02-11 17:36:22 265浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《在Go语言中,如何利用反射从结构体子字段中获取字段数》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

通过 reflect 包从切片结构中的子字段获取项目数时,我遇到了一些问题。

这就是我尝试从 items 获取项目数量的方法

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
  numitems := reflect.valueof(variable.stuff.items)

}

这是错误:

variable.Items undefined (type []Stuff has no field or method Items)

我不确定是否可以检索此类项目的数量。


正确答案


我已经解决了这个问题。

为了获取子字段的数量,我们可以使用 reflect.valueof 中的 len()

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

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

以上就是《在Go语言中,如何利用反射从结构体子字段中获取字段数》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>