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 an interface value, especially an empty interface interface{} (also written any).

The empty interface can hold a value of any type. The dynamic type is the type of the value stored in it, similar to Object in Java or C#.

At compilation time we can’t tell whether that dynamic type is int or string.

Package reflect in the standard library allows us to work with such 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

The basics of reflection are:

Reflection has several practical uses.

Primitive types

Pointers

Structs

Slice

reflect.Kind

Uses for reflection

Feedback about page:

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



Table Of Contents