golang defer 关闭文件 报错file may have nil or other unexpected value as its corresponding error

博客讨论了Go语言中打开文件并确保其正确关闭的最佳实践。错误的示例可能导致`file`在调用`Close()`时为`nil`,引发`panic`。虽然源码显示`file.Close()`内部已经处理了`nil`文件的情况,但IDE仍可能发出警告。正确的做法是在检查`err`不为`nil`之后再使用`defer`关闭文件。

错误实例:

file, err := os.Open("xxx.txt")
defer file.Close()
if err != nil {
       return err
}

初学者很多这样写,但是这样会报错

file’ may have ‘nil’ or other unexpected value as its corresponding error variable may be not ‘nil’

意思是,file可能是nil,调用close会发生panic。正确的做法:

file, err := os.Open("xxx.txt")
if err != nil {
    return
}
defer file.Close()

但是通过看源码,发现file实现的close函数,已经对file等于nil的情况做处理返回ErrInvalid了,所以实际是不会发生panic的,但是goland ide提示以上的报错是因为一般情况下,对于在检测err是否不为nil前做close处理确实会发生panic的,因为对象时nil时做调用。

go1.13.7 /Go/src/os/file_unix.go:229

// Close closes the File, rendering it unusable for I/O.
// On files that support SetDeadline, any pending I/O operations will
// be canceled and return immediately with an error.
// Close will return an error if it has already been called.
func (f *File) Close() error {
    if f == nil {
        return ErrInvalid
    }
    return f.file.close()
}

源码里这种处理,可能是觉得file实现的close是高频调用函数,怕新手在调用时不符合规范而造成panic发生,因此这里做了特殊的处理。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值