Go指向接口的指针不为null [英] Go pointer to interface is not null

查看:59
本文介绍了Go指向接口的指针不为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以提供有关此代码行为的一些解释: https://play.golang.org/p/_TjQhthHl3

Can someone provide some explanation about this code behaviour: https://play.golang.org/p/_TjQhthHl3

package main

import (
    "fmt"
)

type MyError struct{}
func (e *MyError) Error() string {
    return "some error"
}

func main() {
    var err error
    if err == nil {
        fmt.Println("[OK] err is nil ...")
    }else{
        fmt.Println("[KO] err is NOT nil...")
    }
    isNil(err)


    var err2 *MyError
    if err2 == nil {
        fmt.Println("[OK] err2 is nil ...")
    }else{
        fmt.Println("[KO] err2 is NOT nil...")
    }
    isNil(err2)
}

func isNil(err error){
    if err == nil {
        fmt.Println("[OK] ... still nil")
    }else{
        fmt.Println("[KO] .. why not nil?")
    }
}

输出为:

[OK] err is nil ...
[OK] ... still nil
[OK] err2 is nil ...
[KO] .. why err2 not nil?

我发现了此帖子在Go中检查nil和nil接口但我还是不明白...

I found this post Check for nil and nil interface in Go but I still don't get it...

推荐答案

error 是内置接口,而 * MyError 实现该接口.即使 err2 的值为nil,当您将其传递给 isNil 时,该函数也会获得一个非null的接口值.该值包含有关类型( * MyError )和值本身(为nil指针)的信息.

error is a built-in interface, and *MyError implements that interface. Even though the value of err2 is nil, when you pass it to isNil, the function gets a non-nil interface value. That value contains information about the type (*MyError) and the value itself, which is a nil pointer.

如果尝试在 isNil 中打印 err ,则在第二种情况下,即使 err2 为零.这说明了为什么 err 在这种情况下不为零(它必须包含类型信息).

If you try printing err in isNil, you'll see that in the second case, you get "some error" even though err2 is nil. This demonstrates why err is not nil in that case (it has to contain the type information).

这篇关于Go指向接口的指针不为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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