1

I have a struct with methods defined in it, i want to iterate through all the methods. Can i use interface {} or any other way to achieve this ?

type SomeStruct struct {
   m_boolVals []bool
   m_stringVals []string
   m_intVals []int64
   }

func (m *SomeStruct) GetBool() []bool {
    return m.m_boolVals
}

func (m *SomeStruct) GetString() []string {
    return m_stringVals
}

func (m *SomeStruct) GetInts() []int64 {
    return m_intVals 
}

Is there a way to achieve below code ? So basically only one of value would be present

fun SomeOtherFunc(ss *SomeStruct) []string {
    var final_string []string
    for _, handlerFunc := range(ss.GetBool, ss.GetString, ss.GetInts) {
        generic_vals := handlerFunc()
        if (len(generic_vals) > 0) {
            for _, t_val := range(generic_vals)  {
                final_string = append(final_string , string(t_val))
            }
            break
        }
    }
    return final_string
}
Ronin Goda
  • 234
  • 5
  • 13

1 Answers1

2

Here's an example how you can use reflection to iterate over the methods and call each, and convert their result to string:

func SomeOtherFunc(ss *SomeStruct) []string {
    var result []string
    v := reflect.ValueOf(ss)
    for i := 0; i < v.NumMethod(); i++ {
        for _, res := range v.Method(i).Call(nil) {
            result = append(result, fmt.Sprint(res.Interface()))
        }
    }
    return result
}

Testing it:

fmt.Println(SomeOtherFunc(&SomeStruct{
    m_boolVals:   []bool{true, false},
    m_stringVals: []string{"one", "two"},
    m_intVals:    []int64{1, 2, 3},
}))

Which outputs (try it on the Go Playground):

[[true false] [1 2 3] [one two]]
icza
  • 389,944
  • 63
  • 907
  • 827