英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论