dongzhi1904 2015-02-20 04:10
浏览 17
已采纳

满足错误接口的结构的此nil实例未显示为nil

This should be a gimme for someone. Why do I not get what I expect ("Error is not nil") here?

http://play.golang.org/p/s8CWQxobVL

type Goof struct {}

func (goof *Goof) Error() string {
    return fmt.Sprintf("I'm a goof")
}

func TestError(err error) {
    if err == nil {
        fmt.Println("Error is nil")
    } else {
        fmt.Println("Error is not nil")
    }
}

func main() {
    var g *Goof // nil
    TestError(g) // expect "Error is nil"
}
  • 写回答

1条回答 默认 最新

  • dongtui9168 2015-02-20 04:52
    关注

    This is, it turns out, a Frequently Asked Question about Go, and the short answer is that interface comparisons compare the type and the value, and (*Goof)(nil) and error(nil) have different types.

    Since if err != nil is standard, you want a return value that'll work with it. You could declare var err error instead of var g *Goof: err's zero value is conveniently error(nil)

    Or, if your func returns an error, return nil will return what you want.

    For more background, here's the start of the FAQ's answer:

    Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).

    An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type. If we store a pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil). Such an interface value will therefore be non-nil even when the pointer inside is nil.

    And == is strictly checking if the types are identical, not if a type (*Goof) implements an interface (error). Check out the original for more.

    If it helps clarify, this doesn't only happen with nil: in this example, the data underlying the x and y variables is obviously 3, but they have different types. When you put x and y into interface{}s, they compare as unequal:

    package main
    
    import "fmt"
    
    type Bob int
    
    func main() {
        var x int = 3
        var y Bob = 3
        var ix, iy interface{} = x, y
        fmt.Println(ix == iy)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗