0

I want to test the fields in a struct returned from a web API. To do this I need to iterate over the fields in the struct instance Top. How do I do this?

My struct looks like this:

type Top struct {
    A1 Mid,
    A2 Mid,
    A3 Mid,
}

type Mid struct {
   B1 string,
   B2 int64,
   B3 float64
}

My intuition is to do something like this:

M1 := Mid{"a", 1, 1.9}
M2 := Mid{"b", 2, 3.8}
M3 := Mid{"c", 3, 5.7}

T := Top{M1, M2, M3}
S := reflect.ValueOf(&T).Elem()
for i := 0; i < S.NumField(); i++ {
    m := S.Field(i)
    verifyValuesOfMid(&m)
}

This works. But now I have a different problem. Let's say I find an instance of Mid in Top T that is invalid. I want to print out the name of that instance (M2). Is there a way to do this?

Nik Kunkel
  • 335
  • 7
  • 14
  • 2
    Looks fine to me. – Hemel Dec 12 '16 at 23:38
  • M2 is only the name of the lexical variable in that scope. By the time the value is in the Top structure, there is no trace of where the value came from, and even if there was, that'd just be a pointer address at best, as Go does not have a mechanism for introspecting lexical scopes. If you really need "M2" instead of "A2" (which you can get by [reflecting the type](https://stackoverflow.com/questions/24337145/get-name-of-struct-field-using-reflection)), you can use something like a `map[*Mid]string` and assign `m[&T.A2] = "M2"` to keep track of these yourself. – nothingmuch Dec 13 '16 at 06:42

0 Answers0