doujia1904 2013-10-11 11:24
浏览 87
已采纳

将nil指针发送给chan,但接收到“ non-nil”

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    errChan := make(chan error)
    go func() {
        var e *exec.Error = nil
        errChan <- e
    }()
    err := <-errChan
    if err != nil {
        fmt.Printf("err != nil, but err = %v
", err)
    }
}

The output is weird: err != nil, but err = <nil> Try it here: http://play.golang.org/p/_iyh0m7O1a

  • 写回答

2条回答 默认 最新

  • dsaj20411 2013-10-11 11:36
    关注

    The problem lies in that the value passed into the channel as a error interface is not nil, but rather a exec.Error pointer which points to nil.

    The program will behave correctly if you change:

    go func() {
        var e *exec.Error = nil
        if e == nil {
            errChan <- nil
        }
    }()
    

    This is the appropriate way to solve the problem because the idiomatic way to report that no error occurred is by passing a nil error interface.

    However, if you want to change the main instead (maybe because you use a third party package which makes the mistake of returning pointers set to nil), you will have to either do a type assertion to the specific type (*exec.Error) and then check if it is nil, or else use the reflect package.

    Example using reflect to check for nil:

    func IsNil(i interface{}) bool {
        // Check if it is an actual nil-value
        if i == nil {
            return true
        }
    
        v := reflect.ValueOf(i)
        switch v.Kind() {
            // Only the following kinds can be nil
            case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
            return v.IsNil()        
        }
    
        return false
    }
    

    Working example: http://play.golang.org/p/rpG1PVTwwM

    You can find a discussion about it here: https://groups.google.com/forum/#!topic/golang-nuts/QzVDKv7p0Vs

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?