代码之家  ›  专栏  ›  技术社区  ›  Paul Razvan Berg

在go中,为什么打印时反射值和它的界面是相同的?

  •  0
  • Paul Razvan Berg  · 技术社区  · 6 年前

    节选自 Laws of Reflection :

    (为什么不是fmt.Println(v)?因为v是一个反射值;我们想要 具体价值。)

    这让我很困惑,因为下面的代码:

    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)
    

    打印相同的输出:

    x值为:3.4

    x值的界面为:3.4

    是因为 fmt 在内部查找反射的 v ?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Leon    6 年前

    这是一个特例,记录在 String() 方法 reflect.Value

    推荐文章