Pointers
suggest changeA 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'.
reflect.ValueOf unwraps an interface{} argument and returns the concrete value, so the kind is not reflect.Interface. Elem unwraps interface kind only when the reflect.Value is the interface variable itself, for example reflect.ValueOf(&i).Elem() where i has an interface type. An interface value is a type-and-value pair, not a Go pointer.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents