实例:
file, err := os.Open("writeAt.txt")
if err != nil {
panic(err)
}
defer file.Close()
查看源码发现,go标准包中,如果打开文件出错,将返回nil的文件类型,而nil类型的变量调用Close()方法时本身会发生panic。源码:
func OpenFile(name string, flag int, perm FileMode) (*File, error) {
if name == "" {
return nil, &PathError{"open", name, syscall.ENOENT}
}
r, errf := openFile(name, flag, perm)
if errf == nil {
return r, nil
}
r, errd := openDir(name)
if errd == nil {
if flag&O_WRONLY != 0 || flag&O_RDWR != 0 {
r.Close()
return nil, &PathError{"open", name, syscall.EISDIR}
}
return r, nil
}
return nil, &PathError{"open", name, errf}
}