Golang Go语言中 os.File 的疑问

Golang Go语言中 os.File 的疑问

go 标准库中的 os.File 内部实现如下:

type File struct {
	*file // os specific
}

type file struct {
	pfd         poll.FD
	name        string
	dirinfo     *dirInfo // nil unless directory being read
	nonblock    bool     // whether we set nonblocking mode
	stdoutOrErr bool     // whether this is stdout or stderr
	appendMode  bool     // whether file is opened for appending
}

我的疑问是,为什么不直接用下面的方式

type File struct {
	pfd         poll.FD
	name        string
	dirinfo     *dirInfo // nil unless directory being read
	nonblock    bool     // whether we set nonblocking mode
	stdoutOrErr bool     // whether this is stdout or stderr
	appendMode  bool     // whether file is opened for appending
}

更多关于Golang Go语言中 os.File 的疑问的实战教程也可以访问 https://www.itying.com/category-94-b0.html

9 回复

面向对象开发

更多关于Golang Go语言中 os.File 的疑问的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


小写的是私有属性,类似于 java 中 private,对外暴露的是方法和构造方法都是依靠指针操作,防止外人通过反射修改吧

私有化,可以防止外部修改 file 结构体的值。

原因已经在注释里了:os specific
不同操作系统的文件结构体可能不同,导致结构体大小也不一致,加一个间接指针以后,大小就确定了。

file.go
file_plan9.go
file_posix.go
file_unix.go
file_windows.go

每个平台的文件的定义都不太一样,就分开定义了 file,然后再用一个指针封装到 File 里,屏蔽各平台间的差异

type File struct {
*file // os specific
}
为什么用指针,而不是直接内嵌结构体
type File struct {
file // os specific
}

用指针的话, 实际的 file 是分配在 heap 上的(go runtime 的 heap), 在栈上总是只有8字节的指针, 每次栈返回的时候就只用拷贝指针了

注释里写了啊,os specific

你写的 type file … 只是 unix 的,windows 有不同的定义,plan9 也有不同的定义

关于Go语言中os.File的疑问,很高兴能帮助解答。os.File是Go标准库中os包提供的一个结构体,它表示一个打开的文件对象,可以用来进行文件的读写操作。

首先,os.File包含了文件的描述符、路径名、状态标志等信息,通过它可以执行如读取、写入、关闭文件等操作。创建os.File对象通常通过os.Openos.Createos.OpenFile等函数来实现。

例如,使用os.Open打开一个文件:

file, err := os.Open("example.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

这里,os.Open返回一个*os.File对象和一个错误值。如果文件成功打开,可以通过返回的*os.File对象进行后续操作,如读取内容:

data, err := ioutil.ReadAll(file)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))

注意,在完成文件操作后,一定要调用Close方法关闭文件,以避免资源泄露。通常使用defer语句来确保文件在函数返回前被关闭。

此外,os.File还支持文件锁定、文件状态获取等高级操作,这些功能通过其方法实现,如ChmodSync等。

如果你有更具体的问题或遇到了错误,请提供更详细的描述,以便我能给出更精确的帮助。

回到顶部