dongzhou5344 2017-06-13 21:28
浏览 117
已采纳

Go指向接口的指针不为null [重复]

This question already has an answer here:

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?")
    }
}

Output is:

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

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

</div>
  • 写回答

3条回答 默认 最新

  • douzhi4991 2017-06-13 21:47
    关注

    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.

    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).

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

报告相同问题?