GO os.File 的疑问

2019-12-12 15:17:33 +08:00
 yujianwjj

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
}
3464 次点击
所在节点    Go 编程语言
8 条回复
ArJun
2019-12-12 15:22:25 +08:00
面向对象开发
airfling
2019-12-12 15:24:46 +08:00
小写的是私有属性,类似于 java 中 private,对外暴露的是方法和构造方法都是依靠指针操作,防止外人通过反射修改吧
magua
2019-12-12 15:26:44 +08:00
私有化,可以防止外部修改 file 结构体的值。
codehz
2019-12-12 15:29:55 +08:00
原因已经在注释里了:os specific
不同操作系统的文件结构体可能不同,导致结构体大小也不一致,加一个间接指针以后,大小就确定了。
heimeil
2019-12-12 15:38:32 +08:00
file.go
file_plan9.go
file_posix.go
file_unix.go
file_windows.go

每个平台的文件的定义都不太一样,就分开定义了 file,然后再用一个指针封装到 File 里,屏蔽各平台间的差异
yujianwjj
2019-12-12 15:43:07 +08:00
type File struct {
*file // os specific
}
为什么用指针,而不是直接内嵌结构体
type File struct {
file // os specific
}
monsterxx03
2019-12-12 16:10:06 +08:00
用指针的话, 实际的 file 是分配在 heap 上的(go runtime 的 heap), 在栈上总是只有8字节的指针, 每次栈返回的时候就只用拷贝指针了
reus
2019-12-12 16:37:54 +08:00
注释里写了啊,os specific

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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/628381

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX