Essential Go Reflection  Suggest an edit

Pointers

A pointer to X is a distinct type from X.

If reflect.Value references a pointer to a value, you can get a reference to the value by calling Elem().

func printIntResolvingPointers(v interface{}) {
	rv := reflect.ValueOf(v)
	typeName := rv.Type().String()
	name := ""
	for rv.Kind() == reflect.Ptr {
		name = "pointer to " + name
		rv = rv.Elem()
	}
	name += rv.Type().String()
	fmt.Printf("Value: %d. Type: '%s' i.e. '%s'.\n\n", rv.Int(), name, typeName)
}

func main() {
	n := 3
	printIntResolvingPointers(n)

	n = 4
	printIntResolvingPointers(&n)

	n = 5
	np := &n
	printIntResolvingPointers(&np)
}
Value: 3. Type: 'int' i.e. 'int'.

Value: 4. Type: 'pointer to int' i.e. '*int'.

Value: 5. Type: 'pointer to pointer to int' i.e. '**int'.

Under the hood an interface is also a pointer to its underlying value so Elem() also works on reflect.Value representing interface.

  ↑ ↓ to navigate     ↵ to select     Esc to close