簡體   English   中英

如何使用 go 中的反射從結構子字段中獲取項目數

[英]How to get the number of items from a structure sub field using reflect in go

通過reflect package 從切片結構中的子字段獲取項目數時遇到一些問題。

這就是我試圖從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM