Reflection
suggest changeGo is a statically typed language. In most cases the type of a variable is known at compilation time.
One exception is interface type, especially empty interface interface{}
.
Empty interface is a dynamic type, similar to Object
in Java or C#.
At compilation time we can’t tell if the underlying value of interface type is an int
or a string
.
Package reflect
in standard library allows us to work with such dynamic values at runtime. We can:
- inspect the type of dynamic value
- enumerate fields of a struct
- set the value
- create new values at runtime
Related language-level functionality for inspecting type of an interface value at runtime is a type switch and a type assertion.
var v interface{} = 4
var reflectVal reflect.Value = reflect.ValueOf(v)
var typ reflect.Type = reflectVal.Type()
fmt.Printf("Type '%s' of size: %d bytes\n", typ.Name(), typ.Size())
if typ.Kind() == reflect.Int {
fmt.Printf("v contains value of type int\n")
}
Type 'int' of size: 8 bytes
v contains value of type int
Basics of reflections are:
- start with value of empty interface
interface{}
type - use
reflect.ValueOf(v interface{})
to getreflect.Value
which represents information about the value - use
reflect.Value
to check the type of value, test if the value isnil
, set the value
Reflection has several practical uses.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents