亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 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 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號