dongliao4353 2018-01-24 10:51
浏览 36
已采纳

为什么Golang在使用不同的输出功能时显示不同的值

I try to check when Golang return a local value as nil, then I use this code.

package main

import (
    "fmt"
)

type S struct{}

func InitEfacePointer() interface{} {
    var s *S
    println(s)
    return s
}

func main() {
    s := InitEfacePointer()
    fmt.Println(s)
    //println(s)
}

The output is 0x0

But when I just use println to output value.

package main

type S struct{}

func InitEfacePointer() interface{} {
    var s *S
    println(s)
    return s
}

func main() {
    s := InitEfacePointer()
    println(s)
}

The output changed to 0x0 (0x93d40,0x0)

Could anyone explain the mechanism of this behavior? Thanks!

  • 写回答

2条回答 默认 最新

  • dongyonglie5132 2018-01-24 11:19
    关注

    First of all, fmt.Println and builtin println are very different matteres: they are different both in implentation and in purpose. fmt.Println deals with many complex cases using reflect while println only deal with some base cases and is only for "bootstrap or debug" (as the spec says).

    In this specific case, you are printing an interface{} you returned from InitEfacePointer(). The fmt.Println looks into the interface using reflect and gets the underlying data: a nil pointer to a string and it then prints it out: 0x0. On the other hand, builtin println takes the interface and by magic of the compiler (or not), it recognize it is an interface. As this post, golang interface are auctually two pointers, one to information about the type stored and one to the underlying data. So the builtin printlngoes into the interface details, 0x93d40 being the "type info" and 0x0 being the underlying data. (The first 0x0 is from the function call).

    Furthermore, testing whether the returned interface is nil seems like a common mistake. Read here: https://golang.org/doc/faq#nil_error

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM