为什么Golang在使用不同的输出功能时显示不同的值 [英] Why Golang display different values when use different output function

查看:49
本文介绍了为什么Golang在使用不同的输出功能时显示不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试检查Golang何时返回本地值为nil,然后使用此代码.

 程序包主要进口 ("fmt")S型结构{}func InitEfacePointer()接口{} {var s * S打印信息返回s}func main(){s:= InitEfacePointer()fmt.Println(s)//println(s)} 

输出为0x0

但是当我只使用println输出值时.

 程序包主要S型结构{}func InitEfacePointer()接口{} {var s * S打印信息返回s}func main(){s:= InitEfacePointer()打印信息} 

输出更改为0x0(0x93d40,0x0)

有人可以解释这种行为的机制吗?谢谢!

解决方案

首先, fmt.Println 和内置的 println 是非常不同的事情:它们两者都不同专心致志和有目的. fmt.Println 使用反射处理许多复杂的情况,而 println 仅处理一些基本情况,并且仅用于引导或调试"(如规范所述).

在这种情况下,您要打印从 InitEfacePointer()返回的界面{} . fmt.Println 使用反射查看界面并获取基础数据:指向字符串的nil指针,然后将其打印出来: 0x0 .另一方面,内置的 println 带有接口,并且通过编译器的魔力(或没有魔力),它识别出它是一个接口.正如这篇文章一样,golang接口实际上是两个指针,一个指向存储类型的信息,另一个指向存储类型的信息.基础数据.因此,内置的 println 进入了接口详细信息,其中 0x93d40 是类型信息",而 0x0 是基础数据.(第一个 0x0 来自函数调用).

此外,测试返回的接口是否为 nil 似乎是一个常见错误.在这里阅读: https://golang.org/doc/faq#nil_error

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!

解决方案

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

这篇关于为什么Golang在使用不同的输出功能时显示不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆