Reflection

You can find all the code for this chapter here

From Twitter

golang challenge: write a function walk(x interface{}, fn func(string)) which takes a struct x and calls fn for all strings fields found inside. difficulty level: recursively.

To do this we will need to use reflection.

Reflection in computing is the ability of a program to examine its own structure, particularly through types; it’s a form of metaprogramming. It’s also a great source of confusion.

From The Go Blog: Reflection

What is interface{}?

We have enjoyed the type-safety that Go has offered us in terms of functions that work with known types, such as string, int and our own types like BankAccount.

This means that we get some documentation for free and the compiler will complain if you try and pass the wrong type to a function.

You may come across scenarios though where you want to write a function where you don’t know the type at compile time.

Go lets us get around this with the type interface{} which you can think of as just any type (in fact, in Go any is an alias for interface{}).

So walk(x interface{}, fn func(string)) will accept any value for x.

So why not use interface{} for everything and have really flexible functions?

  • As a user of a function that takes interface{} you lose type safety. What if you meant to pass Foo.bar of type string into a function but instead did Foo.baz which is an int? The compiler won’t be able to inform you of your mistake. You also have no idea what you’re allowed to pass to a function. Knowing that a function takes a UserService for instance is very useful.
  • As a writer of such a function, you have to be able to inspect anything that has been passed to you and try and figure out what the type is and what you can do with it. This is done using reflection. This can be quite clumsy and difficult to read and is generally less performant (as you have to do checks at runtime).

In short only use reflection if you really need to.

If you want polymorphic functions, consider if you could design it around an interface (not interface{}, confusingly) so that users can use your function with multiple types if they implement whatever methods you need for your function to work.

Our function will need to be able to work with lots of different things. As always we’ll take an iterative approach, writing tests for each new thing we want to support and refactoring along the way until we’re done.

Write the test first

We’ll want to call our function with a struct that has a string field in it (x). Then we can spy on the function (fn) passed in to see if it is called.

  1. func TestWalk(t *testing.T) {
  2. expected := "Chris"
  3. var got []string
  4. x := struct {
  5. Name string
  6. }{expected}
  7. walk(x, func(input string) {
  8. got = append(got, input)
  9. })
  10. if len(got) != 1 {
  11. t.Errorf("wrong number of function calls, got %d want %d", len(got), 1)
  12. }
  13. }
  • We want to store a slice of strings (got) which stores which strings were passed into fn by walk. Often in previous chapters, we have made dedicated types for this to spy on function/method invocations but in this case, we can just pass in an anonymous function for fn that closes over got.
  • We use an anonymous struct with a Name field of type string to go for the simplest “happy” path.
  • Finally, call walk with x and the spy and for now just check the length of got, we’ll be more specific with our assertions once we’ve got something very basic working.

Try to run the test

  1. ./reflection_test.go:21:2: undefined: walk

Write the minimal amount of code for the test to run and check the failing test output

We need to define walk

  1. func walk(x interface{}, fn func(input string)) {
  2. }

Try and run the test again

  1. === RUN TestWalk
  2. --- FAIL: TestWalk (0.00s)
  3. reflection_test.go:19: wrong number of function calls, got 0 want 1
  4. FAIL

Write enough code to make it pass

We can call the spy with any string to make this pass.

  1. func walk(x interface{}, fn func(input string)) {
  2. fn("I still can't believe South Korea beat Germany 2-0 to put them last in their group")
  3. }

The test should now be passing. The next thing we’ll need to do is make a more specific assertion on what our fn is being called with.

Write the test first

Add the following to the existing test to check the string passed to fn is correct

  1. if got[0] != expected {
  2. t.Errorf("got %q, want %q", got[0], expected)
  3. }

Try to run the test

  1. === RUN TestWalk
  2. --- FAIL: TestWalk (0.00s)
  3. reflection_test.go:23: got 'I still can't believe South Korea beat Germany 2-0 to put them last in their group', want 'Chris'
  4. FAIL

Write enough code to make it pass

  1. func walk(x interface{}, fn func(input string)) {
  2. val := reflect.ValueOf(x)
  3. field := val.Field(0)
  4. fn(field.String())
  5. }

This code is very unsafe and very naive, but remember: our goal when we are in “red” (the tests failing) is to write the smallest amount of code possible. We then write more tests to address our concerns.

We need to use reflection to have a look at x and try and look at its properties.

The reflect package has a function ValueOf which returns us a Value of a given variable. This has ways for us to inspect a value, including its fields which we use on the next line.

We then make some very optimistic assumptions about the value passed in

  • We look at the first and only field, there may be no fields at all which would cause a panic
  • We then call String() which returns the underlying value as a string but we know it would be wrong if the field was something other than a string.

Refactor

Our code is passing for the simple case but we know our code has a lot of shortcomings.

We’re going to be writing a number of tests where we pass in different values and checking the array of strings that fn was called with.

We should refactor our test into a table based test to make this easier to continue testing new scenarios.

  1. func TestWalk(t *testing.T) {
  2. cases := []struct {
  3. Name string
  4. Input interface{}
  5. ExpectedCalls []string
  6. }{
  7. {
  8. "struct with one string field",
  9. struct {
  10. Name string
  11. }{"Chris"},
  12. []string{"Chris"},
  13. },
  14. }
  15. for _, test := range cases {
  16. t.Run(test.Name, func(t *testing.T) {
  17. var got []string
  18. walk(test.Input, func(input string) {
  19. got = append(got, input)
  20. })
  21. if !reflect.DeepEqual(got, test.ExpectedCalls) {
  22. t.Errorf("got %v, want %v", got, test.ExpectedCalls)
  23. }
  24. })
  25. }
  26. }

Now we can easily add a scenario to see what happens if we have more than one string field.

Write the test first

Add the following scenario to the cases.

  1. {
  2. "struct with two string fields",
  3. struct {
  4. Name string
  5. City string
  6. }{"Chris", "London"},
  7. []string{"Chris", "London"},
  8. }

Try to run the test

  1. === RUN TestWalk/struct_with_two_string_fields
  2. --- FAIL: TestWalk/struct_with_two_string_fields (0.00s)
  3. reflection_test.go:40: got [Chris], want [Chris London]

Write enough code to make it pass

  1. func walk(x interface{}, fn func(input string)) {
  2. val := reflect.ValueOf(x)
  3. for i := 0; i < val.NumField(); i++ {
  4. field := val.Field(i)
  5. fn(field.String())
  6. }
  7. }

val has a method NumField which returns the number of fields in the value. This lets us iterate over the fields and call fn which passes our test.

Refactor

It doesn’t look like there’s any obvious refactors here that would improve the code so let’s press on.

The next shortcoming in walk is that it assumes every field is a string. Let’s write a test for this scenario.

Write the test first

Add the following case

  1. {
  2. "struct with non string field",
  3. struct {
  4. Name string
  5. Age int
  6. }{"Chris", 33},
  7. []string{"Chris"},
  8. },

Try to run the test

  1. === RUN TestWalk/struct_with_non_string_field
  2. --- FAIL: TestWalk/struct_with_non_string_field (0.00s)
  3. reflection_test.go:46: got [Chris <int Value>], want [Chris]

Write enough code to make it pass

We need to check that the type of the field is a string.

  1. func walk(x interface{}, fn func(input string)) {
  2. val := reflect.ValueOf(x)
  3. for i := 0; i < val.NumField(); i++ {
  4. field := val.Field(i)
  5. if field.Kind() == reflect.String {
  6. fn(field.String())
  7. }
  8. }
  9. }

We can do that by checking its Kind.

Refactor

Again it looks like the code is reasonable enough for now.

The next scenario is what if it isn’t a “flat” struct? In other words, what happens if we have a struct with some nested fields?

Write the test first

We have been using the anonymous struct syntax to declare types ad-hocly for our tests so we could continue to do that like so

  1. {
  2. "nested fields",
  3. struct {
  4. Name string
  5. Profile struct {
  6. Age int
  7. City string
  8. }
  9. }{"Chris", struct {
  10. Age int
  11. City string
  12. }{33, "London"}},
  13. []string{"Chris", "London"},
  14. },

But we can see that when you get inner anonymous structs the syntax gets a little messy. There is a proposal to make it so the syntax would be nicer.

Let’s just refactor this by making a known type for this scenario and reference it in the test. There is a little indirection in that some of the code for our test is outside the test but readers should be able to infer the structure of the struct by looking at the initialisation.

Add the following type declarations somewhere in your test file

  1. type Person struct {
  2. Name string
  3. Profile Profile
  4. }
  5. type Profile struct {
  6. Age int
  7. City string
  8. }

Now we can add this to our cases which reads a lot clearer than before

  1. {
  2. "nested fields",
  3. Person{
  4. "Chris",
  5. Profile{33, "London"},
  6. },
  7. []string{"Chris", "London"},
  8. },

Try to run the test

  1. === RUN TestWalk/Nested_fields
  2. --- FAIL: TestWalk/nested_fields (0.00s)
  3. reflection_test.go:54: got [Chris], want [Chris London]

The problem is we’re only iterating on the fields on the first level of the type’s hierarchy.

Write enough code to make it pass

  1. func walk(x interface{}, fn func(input string)) {
  2. val := reflect.ValueOf(x)
  3. for i := 0; i < val.NumField(); i++ {
  4. field := val.Field(i)
  5. if field.Kind() == reflect.String {
  6. fn(field.String())
  7. }
  8. if field.Kind() == reflect.Struct {
  9. walk(field.Interface(), fn)
  10. }
  11. }
  12. }

The solution is quite simple, we again inspect its Kind and if it happens to be a struct we just call walk again on that inner struct.

Refactor

  1. func walk(x interface{}, fn func(input string)) {
  2. val := reflect.ValueOf(x)
  3. for i := 0; i < val.NumField(); i++ {
  4. field := val.Field(i)
  5. switch field.Kind() {
  6. case reflect.String:
  7. fn(field.String())
  8. case reflect.Struct:
  9. walk(field.Interface(), fn)
  10. }
  11. }
  12. }

When you’re doing a comparison on the same value more than once generally refactoring into a switch will improve readability and make your code easier to extend.

What if the value of the struct passed in is a pointer?

Write the test first

Add this case

  1. {
  2. "pointers to things",
  3. &Person{
  4. "Chris",
  5. Profile{33, "London"},
  6. },
  7. []string{"Chris", "London"},
  8. },

Try to run the test

  1. === RUN TestWalk/pointers_to_things
  2. panic: reflect: call of reflect.Value.NumField on ptr Value [recovered]
  3. panic: reflect: call of reflect.Value.NumField on ptr Value

Write enough code to make it pass

  1. func walk(x interface{}, fn func(input string)) {
  2. val := reflect.ValueOf(x)
  3. if val.Kind() == reflect.Ptr {
  4. val = val.Elem()
  5. }
  6. for i := 0; i < val.NumField(); i++ {
  7. field := val.Field(i)
  8. switch field.Kind() {
  9. case reflect.String:
  10. fn(field.String())
  11. case reflect.Struct:
  12. walk(field.Interface(), fn)
  13. }
  14. }
  15. }

You can’t use NumField on a pointer Value, we need to extract the underlying value before we can do that by using Elem().

Refactor

Let’s encapsulate the responsibility of extracting the reflect.Value from a given interface{} into a function.

  1. func walk(x interface{}, fn func(input string)) {
  2. val := getValue(x)
  3. for i := 0; i < val.NumField(); i++ {
  4. field := val.Field(i)
  5. switch field.Kind() {
  6. case reflect.String:
  7. fn(field.String())
  8. case reflect.Struct:
  9. walk(field.Interface(), fn)
  10. }
  11. }
  12. }
  13. func getValue(x interface{}) reflect.Value {
  14. val := reflect.ValueOf(x)
  15. if val.Kind() == reflect.Ptr {
  16. val = val.Elem()
  17. }
  18. return val
  19. }

This actually adds more code but I feel the abstraction level is right.

  • Get the reflect.Value of x so I can inspect it, I don’t care how.
  • Iterate over the fields, doing whatever needs to be done depending on its type.

Next, we need to cover slices.

Write the test first

  1. {
  2. "slices",
  3. []Profile {
  4. {33, "London"},
  5. {34, "Reykjavík"},
  6. },
  7. []string{"London", "Reykjavík"},
  8. },

Try to run the test

  1. === RUN TestWalk/slices
  2. panic: reflect: call of reflect.Value.NumField on slice Value [recovered]
  3. panic: reflect: call of reflect.Value.NumField on slice Value

Write the minimal amount of code for the test to run and check the failing test output

This is similar to the pointer scenario before, we are trying to call NumField on our reflect.Value but it doesn’t have one as it’s not a struct.

Write enough code to make it pass

  1. func walk(x interface{}, fn func(input string)) {
  2. val := getValue(x)
  3. if val.Kind() == reflect.Slice {
  4. for i := 0; i < val.Len(); i++ {
  5. walk(val.Index(i).Interface(), fn)
  6. }
  7. return
  8. }
  9. for i := 0; i < val.NumField(); i++ {
  10. field := val.Field(i)
  11. switch field.Kind() {
  12. case reflect.String:
  13. fn(field.String())
  14. case reflect.Struct:
  15. walk(field.Interface(), fn)
  16. }
  17. }
  18. }

Refactor

This works but it’s yucky. No worries, we have working code backed by tests so we are free to tinker all we like.

If you think a little abstractly, we want to call walk on either

  • Each field in a struct
  • Each thing in a slice

Our code at the moment does this but doesn’t reflect it very well. We just have a check at the start to see if it’s a slice (with a return to stop the rest of the code executing) and if it’s not we just assume it’s a struct.

Let’s rework the code so instead we check the type first and then do our work.

  1. func walk(x interface{}, fn func(input string)) {
  2. val := getValue(x)
  3. switch val.Kind() {
  4. case reflect.Struct:
  5. for i := 0; i < val.NumField(); i++ {
  6. walk(val.Field(i).Interface(), fn)
  7. }
  8. case reflect.Slice:
  9. for i := 0; i < val.Len(); i++ {
  10. walk(val.Index(i).Interface(), fn)
  11. }
  12. case reflect.String:
  13. fn(val.String())
  14. }
  15. }

Looking much better! If it’s a struct or a slice we iterate over its values calling walk on each one. Otherwise, if it’s a reflect.String we can call fn.

Still, to me it feels like it could be better. There’s repetition of the operation of iterating over fields/values and then calling walk but conceptually they’re the same.

  1. func walk(x interface{}, fn func(input string)) {
  2. val := getValue(x)
  3. numberOfValues := 0
  4. var getField func(int) reflect.Value
  5. switch val.Kind() {
  6. case reflect.String:
  7. fn(val.String())
  8. case reflect.Struct:
  9. numberOfValues = val.NumField()
  10. getField = val.Field
  11. case reflect.Slice:
  12. numberOfValues = val.Len()
  13. getField = val.Index
  14. }
  15. for i := 0; i < numberOfValues; i++ {
  16. walk(getField(i).Interface(), fn)
  17. }
  18. }

If the value is a reflect.String then we just call fn like normal.

Otherwise, our switch will extract out two things depending on the type

  • How many fields there are
  • How to extract the Value (Field or Index)

Once we’ve determined those things we can iterate through numberOfValues calling walk with the result of the getField function.

Now we’ve done this, handling arrays should be trivial.

Write the test first

Add to the cases

  1. {
  2. "arrays",
  3. [2]Profile {
  4. {33, "London"},
  5. {34, "Reykjavík"},
  6. },
  7. []string{"London", "Reykjavík"},
  8. },

Try to run the test

  1. === RUN TestWalk/arrays
  2. --- FAIL: TestWalk/arrays (0.00s)
  3. reflection_test.go:78: got [], want [London Reykjavík]

Write enough code to make it pass

Arrays can be handled the same way as slices, so just add it to the case with a comma

  1. func walk(x interface{}, fn func(input string)) {
  2. val := getValue(x)
  3. numberOfValues := 0
  4. var getField func(int) reflect.Value
  5. switch val.Kind() {
  6. case reflect.String:
  7. fn(val.String())
  8. case reflect.Struct:
  9. numberOfValues = val.NumField()
  10. getField = val.Field
  11. case reflect.Slice, reflect.Array:
  12. numberOfValues = val.Len()
  13. getField = val.Index
  14. }
  15. for i := 0; i < numberOfValues; i++ {
  16. walk(getField(i).Interface(), fn)
  17. }
  18. }

The next type we want to handle is map.

Write the test first

  1. {
  2. "maps",
  3. map[string]string{
  4. "Foo": "Bar",
  5. "Baz": "Boz",
  6. },
  7. []string{"Bar", "Boz"},
  8. },

Try to run the test

  1. === RUN TestWalk/maps
  2. --- FAIL: TestWalk/maps (0.00s)
  3. reflection_test.go:86: got [], want [Bar Boz]

Write enough code to make it pass

Again if you think a little abstractly you can see that map is very similar to struct, it’s just the keys are unknown at compile time.

  1. func walk(x interface{}, fn func(input string)) {
  2. val := getValue(x)
  3. numberOfValues := 0
  4. var getField func(int) reflect.Value
  5. switch val.Kind() {
  6. case reflect.String:
  7. fn(val.String())
  8. case reflect.Struct:
  9. numberOfValues = val.NumField()
  10. getField = val.Field
  11. case reflect.Slice, reflect.Array:
  12. numberOfValues = val.Len()
  13. getField = val.Index
  14. case reflect.Map:
  15. for _, key := range val.MapKeys() {
  16. walk(val.MapIndex(key).Interface(), fn)
  17. }
  18. }
  19. for i := 0; i < numberOfValues; i++ {
  20. walk(getField(i).Interface(), fn)
  21. }
  22. }

However, by design you cannot get values out of a map by index. It’s only done by key, so that breaks our abstraction, darn.

Refactor

How do you feel right now? It felt like maybe a nice abstraction at the time but now the code feels a little wonky.

This is OK! Refactoring is a journey and sometimes we will make mistakes. A major point of TDD is it gives us the freedom to try these things out.

By taking small steps backed by tests this is in no way an irreversible situation. Let’s just put it back to how it was before the refactor.

  1. func walk(x interface{}, fn func(input string)) {
  2. val := getValue(x)
  3. walkValue := func(value reflect.Value) {
  4. walk(value.Interface(), fn)
  5. }
  6. switch val.Kind() {
  7. case reflect.String:
  8. fn(val.String())
  9. case reflect.Struct:
  10. for i := 0; i < val.NumField(); i++ {
  11. walkValue(val.Field(i))
  12. }
  13. case reflect.Slice, reflect.Array:
  14. for i := 0; i < val.Len(); i++ {
  15. walkValue(val.Index(i))
  16. }
  17. case reflect.Map:
  18. for _, key := range val.MapKeys() {
  19. walkValue(val.MapIndex(key))
  20. }
  21. }
  22. }

We’ve introduced walkValue which DRYs up the calls to walk inside our switch so that they only have to extract out the reflect.Values from val.

One final problem

Remember that maps in Go do not guarantee order. So your tests will sometimes fail because we assert that the calls to fn are done in a particular order.

To fix this, we’ll need to move our assertion with the maps to a new test where we do not care about the order.

  1. t.Run("with maps", func(t *testing.T) {
  2. aMap := map[string]string{
  3. "Foo": "Bar",
  4. "Baz": "Boz",
  5. }
  6. var got []string
  7. walk(aMap, func(input string) {
  8. got = append(got, input)
  9. })
  10. assertContains(t, got, "Bar")
  11. assertContains(t, got, "Boz")
  12. })

Here is how assertContains is defined

  1. func assertContains(t testing.TB, haystack []string, needle string) {
  2. t.Helper()
  3. contains := false
  4. for _, x := range haystack {
  5. if x == needle {
  6. contains = true
  7. }
  8. }
  9. if !contains {
  10. t.Errorf("expected %+v to contain %q but it didn't", haystack, needle)
  11. }
  12. }

The next type we want to handle is chan.

Write the test first

  1. t.Run("with channels", func(t *testing.T) {
  2. aChannel := make(chan Profile)
  3. go func() {
  4. aChannel <- Profile{33, "Berlin"}
  5. aChannel <- Profile{34, "Katowice"}
  6. close(aChannel)
  7. }()
  8. var got []string
  9. want := []string{"Berlin", "Katowice"}
  10. walk(aChannel, func(input string) {
  11. got = append(got, input)
  12. })
  13. if !reflect.DeepEqual(got, want) {
  14. t.Errorf("got %v, want %v", got, want)
  15. }
  16. })

Try to run the test

  1. --- FAIL: TestWalk (0.00s)
  2. --- FAIL: TestWalk/with_channels (0.00s)
  3. reflection_test.go:115: got [], want [Berlin Katowice]

Write enough code to make it pass

We can iterate through all values sent through channel until it was closed with Recv()

  1. func walk(x interface{}, fn func(input string)) {
  2. val := getValue(x)
  3. walkValue := func(value reflect.Value) {
  4. walk(value.Interface(), fn)
  5. }
  6. switch val.Kind() {
  7. case reflect.String:
  8. fn(val.String())
  9. case reflect.Struct:
  10. for i := 0; i < val.NumField(); i++ {
  11. walkValue(val.Field(i))
  12. }
  13. case reflect.Slice, reflect.Array:
  14. for i := 0; i < val.Len(); i++ {
  15. walkValue(val.Index(i))
  16. }
  17. case reflect.Map:
  18. for _, key := range val.MapKeys() {
  19. walkValue(val.MapIndex(key))
  20. }
  21. case reflect.Chan:
  22. for v, ok := val.Recv(); ok; v, ok = val.Recv() {
  23. walkValue(v)
  24. }
  25. }
  26. }

The next type we want to handle is func.

Write the test first

  1. t.Run("with function", func(t *testing.T) {
  2. aFunction := func() (Profile, Profile) {
  3. return Profile{33, "Berlin"}, Profile{34, "Katowice"}
  4. }
  5. var got []string
  6. want := []string{"Berlin", "Katowice"}
  7. walk(aFunction, func(input string) {
  8. got = append(got, input)
  9. })
  10. if !reflect.DeepEqual(got, want) {
  11. t.Errorf("got %v, want %v", got, want)
  12. }
  13. })

Try to run the test

  1. --- FAIL: TestWalk (0.00s)
  2. --- FAIL: TestWalk/with_function (0.00s)
  3. reflection_test.go:132: got [], want [Berlin Katowice]

Write enough code to make it pass

Non zero-argument functions do not seem to make a lot of sense in this scenario. But we should allow for arbitrary return values.

  1. func walk(x interface{}, fn func(input string)) {
  2. val := getValue(x)
  3. walkValue := func(value reflect.Value) {
  4. walk(value.Interface(), fn)
  5. }
  6. switch val.Kind() {
  7. case reflect.String:
  8. fn(val.String())
  9. case reflect.Struct:
  10. for i := 0; i < val.NumField(); i++ {
  11. walkValue(val.Field(i))
  12. }
  13. case reflect.Slice, reflect.Array:
  14. for i := 0; i < val.Len(); i++ {
  15. walkValue(val.Index(i))
  16. }
  17. case reflect.Map:
  18. for _, key := range val.MapKeys() {
  19. walkValue(val.MapIndex(key))
  20. }
  21. case reflect.Chan:
  22. for v, ok := val.Recv(); ok; v, ok = val.Recv() {
  23. walkValue(v)
  24. }
  25. case reflect.Func:
  26. valFnResult := val.Call(nil)
  27. for _, res := range valFnResult {
  28. walkValue(res)
  29. }
  30. }
  31. }

Wrapping up

  • Introduced some concepts from the reflect package.
  • Used recursion to traverse arbitrary data structures.
  • Did an in retrospect bad refactor but didn’t get too upset about it. By working iteratively with tests it’s not such a big deal.
  • This only covered a small aspect of reflection. The Go blog has an excellent post covering more details.
  • Now that you know about reflection, do your best to avoid using it.