goreflectiongo-reflectgofmt

In go, why are both the reflected value and its interface the same when printed?


Excerpt from the Laws of Reflection:

(Why not fmt.Println(v)? Because v is a reflect.Value; we want the concrete value it holds.)

This confuses me because the following code:

var x float64 = 3.4
var v = reflect.ValueOf(x)

fmt.Println("value of x is:", v)
y := v.Interface().(float64) // y will have type float64.
fmt.Println("interface of value of x is:", y)

Prints the same output:

value of x is: 3.4

interface of value of x is: 3.4

Is it because fmt internally finds the concrete value for the reflected v?


Solution

  • This is a special case, which is documented on the String() method of reflect.Value. It states

    The fmt package treats Values specially. It does not call their String method implicitly but instead prints the concrete values they hold.