Reflection is the ability to inspect a value to derive type or other meta-data. Reflection can give our program incredible flexibility to work with data of different types or create values on the fly. Reflection is critical for the encoding and decoding of data.
- The reflection package allows us to inspect our types.
- We can add "tags" to our struct fields to store and use meta-data.
- Encoding package leverages reflection and we can as well.
The Laws of Reflection - Rob Pike
Example shows how to reflect over a struct type value that is stored inside an interface value.
Struct Types (Go Playground)
Example shows how to reflect over a slice of struct type values that are stored inside an interface value.
Slices (Go Playground)
Example shows how to reflect over a map of struct type values that are stored inside an interface value.
Maps (Go Playground)
Example shows how to reflect over a struct type pointer that is stored inside an interface value.
Pointers (Go Playground)
Example shows how to reflect on a struct type with tags.
Tags (Go Playground)
Example shows how to inspect a structs fields and display the field name, type and value.
Struct Types (Go Playground)
Example shows how to use reflection to decode an integer.
Integers (Go Playground)
Declare a struct type that represents a request for a customer invoice. Include a CustomerID and InvoiceID field. Define tags that can be used to validate the request. Define tags that specify both the length and range for the ID to be valid. Declare a function named validate that accepts values of any type and processes the tags. Display the results of the validation.
Template (Go Playground) | Answer (Go Playground)
All material is licensed under the Apache License Version 2.0, January 2004.