3

How to list the fields and methods of a struct, in GoLang dynamically? For eg, I want to get the output as id, name, age, and all the method names.

type Student struct {
    id int
    name string
    age int
}

func (s *Student) setId(i int) {
    s.id = i
}

func (s *Student) getId() int {
    return s.id
}

func (s *Student) setName(n string) {
    s.name = n
}

func (s *Student) getName() string {
    return s.name
}

func (s *Student) setAge(a int) {
    s.age = a
}

func (s *Student) getAge() int {
    return s.age
}

func main() {
    st := Student{1,"Jack",22}
    fmt.Println(st.getId()," ",st.getName()," ",st.getAge())

}
Yajnesh Rai
  • 290
  • 1
  • 6
  • 17

1 Answers1

4

To get information about a struct at runtime, you have to use the package reflect. First, get the type of the struct, and then you can iterate through it. However, with your example, be aware that the type main.Student doesn't have any methods associated, but the type *main.Student has.

Here is an example of how you can fetch those information:

func main() {
    s := Student{1, "Jack", 22}
    t := reflect.TypeOf(s)
    ptr_t := reflect.TypeOf(&s)

    methods := make([]string, 0)
    for i := 0; i < ptr_t.NumMethod(); i++ {
        methods = append(methods, ptr_t.Method(i).Name)
    }

    fields := make([]string, 0)
    for i := 0; i < t.NumField(); i++ {
        fields = append(fields, t.Field(i).Name)
    }

    fmt.Println(methods)
    # [getAge getId getName setAge setId setName]
    fmt.Println(fields)
    # [id name age]

}

A point about your code: look at how the export of fields and methods between package is done. Because all the fields and methods starting by a lowercase letter are not accessible outside of the package. You have to start them with an uppercase letter.

Another point: there are usually no getters and setters in Go code. If you want to read and write a struct field, simply start it with an uppercase letter.

T. Claverie
  • 11,380
  • 1
  • 17
  • 28