我怎么知道golang中结构的长度?

How can i know the length of struct in golang?

我是 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" 
}

您可以为此使用 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() 获取结构在内存中占用的字节数。

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

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())
}