Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

io.Close 章节关于 defer file.Close() 解释有问题吧? #40

Closed
islishude opened this issue Jan 24, 2018 · 3 comments
Closed

io.Close 章节关于 defer file.Close() 解释有问题吧? #40

islishude opened this issue Jan 24, 2018 · 3 comments

Comments

@islishude
Copy link

原文链接:https://books.studygolang.com/The-Golang-Standard-Library-by-Example/chapter01/01.1.html#closer%E6%8E%A5%E5%8F%A3

2018-01-24 3 42 04

defer file.Close() 是在函数最后阶段执行,无论是放在错误检查前后行为都是一致的吧,不会有错误吧!?

求教。

@snaigle
Copy link

snaigle commented Jan 24, 2018

defer file.Close() 应该放到err检查之后
当 open 出错时, file 为nil ,这里调用file.Close() 会返回err ,并不会panic

@islishude
Copy link
Author

@snaigle 这里调用的 defer file.Close() ,放在 err 检查的前后并没有什么区别的吧。

@polaris1119
Copy link
Owner

polaris1119 commented Jan 25, 2018

我确认了下,之所以在 error 之前 file.Close 没有问题,是因为 Close 的实现是这样的:

func (f *File) Close() error {
  	if f == nil {
  		return ErrInvalid
  	}
  	return f.file.close()
 }

一般里说,对一个 nil 对象,调用它的方法,会出问题的。

但这块的解释,确实需要稍微改下。但先判断错误,在 defer file.Close() 绝对是正确的做法,养成这样的习惯吧。

已加注释。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants