Reflection:
*
Pointers
*
Structs
*
Slice
Go 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:
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:
interface{} type
reflect.ValueOf(v interface{}) to get reflect.Value which represents information about the value
reflect.Value to check the type of value, test if the value is nil, set the value
Reflection has several practical uses.