Home > Software engineering >  How can i know the length of struct in golang?
How can i know the length of struct in golang?

Time:11-29

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related