Reflection

suggest change

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:

Reflection has several practical uses.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents