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

52 views Asked by At

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?

1

There are 1 answers

1
Leon On BEST ANSWER

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.