How can i know the length of struct in golang?

huangapple go评论87阅读模式
英文:

How can i know the length of struct in golang?

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我是Go语言的新手,我正在尝试从一个结构体中获取多个属性。例如:

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.getLengthAttributes()) //它将打印出"3"
}

请注意,代码中的 fmt.println 应该是 fmt.Println

英文:

I am new to Golang and I am trying to get a number of attributes from a structure
For example:

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

答案1

得分: 4

使用reflect包的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("结构体有 %d 个字段", v.NumField())
}
英文:

Using the reflect package's ValueOf() function returns a value struct. This has a method called NumFields that returns the number of fields.

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

得分: 1

你可以使用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()可以得到结构体在内存中占用的字节数。

英文:

You can use the reflect package for this:

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

This is not, however, the size of that struct, only the number of fields. Use reflect.TypeOf(client).Size() to get how many bytes the struct occupies in memory.

huangapple
  • 本文由 发表于 2021年11月29日 06:02:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/70147846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定