【问题标题】:How can i know the length of struct in golang?我怎么知道golang中struct的长度?
【发布时间】:2022-01-05 21:33:42
【问题描述】:

我是 Golang 的新手,我正在尝试从结构中获取一些属性 例如:

type Client struct{
    name string//1
    lastName string//2
    age uint//3
}
func main(){
    client := Client{name:"Facundo",lastName:"Veronelli",age:23}
    fmt.println(client.getLengthAttibutes())//It would print "3" 
}

【问题讨论】:

    标签: go struct


    【解决方案1】:

    使用反射包的ValueOf() 函数返回一个value 结构。这有一个名为 NumFields 的方法,它返回字段数。

    import (
      "fmt"
      "reflect"
    )
    
    type Client struct{
        name string//1
        lastName string//2
        age uint//3
    }
    
    func main(){
        client := Client{name:"Facundo",lastName:"Veronelli",age:23}
        v := reflect.ValueOf(client)
        fmt.Printf("Struct has %d fields", v.NumField())
    }
    

    【讨论】:

      【解决方案2】:

      您可以为此使用reflect 包:

      import (
          "fmt"
          "reflect"
      )
      
      type Client struct {
          name     string //1
          lastName string //2
          age      uint   //3
      }
      
      func main() {
          client := Client{name: "Facundo", lastName: "Veronelli", age: 23}
          fmt.Println(reflect.TypeOf(client).NumField())
      }
      

      然而,这不是该结构的大小,而只是字段的数量。使用reflect.TypeOf(client).Size() 获取该结构在内存中占用的字节数。

      【讨论】:

        猜你喜欢
        • 2018-08-08
        • 1970-01-01
        • 1970-01-01
        • 2015-12-31
        • 2017-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多