go - 在go中,为什么打印出来的reflected value和它的interface一样?

标签 go reflection go-reflect gofmt

摘自 Laws of Reflection :

(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()reflect.Value的方法.它指出

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

关于go - 在go中,为什么打印出来的reflected value和它的interface一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52477377/

相关文章:

go - 我的 go 代码有什么问题(IO 等待)?

docker 检查 : how to select only certain keys from range

java - 基于反射的基本通用 DAO

c# - 如何为引用和值类型创建属性表达式?

go - 在 golang 中,是否可以从类型本身获取 reflect.Type,从名称作为字符串?

google-app-engine - 有没有人能够获得Go Hello World快速入门演示,使其适用于Google App Engine托管的VM?

c# - 检查对象是否满足通用参数约束

go - 从反射类型创建 slice

pointers - 将 reflect.AppendSlice 的结果分配给指针

arrays - Go语言中的结构体数组