在go中,为什么打印出来的reflected value和它的interface一样?
In go, why are both the reflected value and its interface the same when printed?
(Why not fmt.Println(v)? Because v is a reflect.Value; we want the
concrete value it holds.)
这让我很困惑,因为下面的代码:
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)
打印相同的输出:
value of x is: 3.4
interface of value of x is: 3.4
是不是因为fmt
内部找到了反射的具体值v
?
这是一个特例,在String()
method of reflect.Value
上有记载。它指出
The fmt package treats Values specially. It does not call their String method implicitly but instead prints the concrete values they hold.
(Why not fmt.Println(v)? Because v is a reflect.Value; we want the concrete value it holds.)
这让我很困惑,因为下面的代码:
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)
打印相同的输出:
value of x is: 3.4
interface of value of x is: 3.4
是不是因为fmt
内部找到了反射的具体值v
?
这是一个特例,在String()
method of reflect.Value
上有记载。它指出
The fmt package treats Values specially. It does not call their String method implicitly but instead prints the concrete values they hold.