V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
yujianwjj
V2EX  ›  Go 编程语言

GO os.File 的疑问

  •  
  •   yujianwjj · 2019-12-12 15:17:33 +08:00 · 3452 次点击
    这是一个创建于 1569 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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
    }
    
    8 条回复    2019-12-12 16:37:54 +08:00
    ArJun
        1
    ArJun  
       2019-12-12 15:22:25 +08:00
    面向对象开发
    airfling
        2
    airfling  
       2019-12-12 15:24:46 +08:00
    小写的是私有属性,类似于 java 中 private,对外暴露的是方法和构造方法都是依靠指针操作,防止外人通过反射修改吧
    magua
        3
    magua  
       2019-12-12 15:26:44 +08:00
    私有化,可以防止外部修改 file 结构体的值。
    codehz
        4
    codehz  
       2019-12-12 15:29:55 +08:00 via Android
    原因已经在注释里了:os specific
    不同操作系统的文件结构体可能不同,导致结构体大小也不一致,加一个间接指针以后,大小就确定了。
    heimeil
        5
    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
        6
    yujianwjj  
    OP
       2019-12-12 15:43:07 +08:00
    type File struct {
    *file // os specific
    }
    为什么用指针,而不是直接内嵌结构体
    type File struct {
    file // os specific
    }
    monsterxx03
        7
    monsterxx03  
       2019-12-12 16:10:06 +08:00
    用指针的话, 实际的 file 是分配在 heap 上的(go runtime 的 heap), 在栈上总是只有8字节的指针, 每次栈返回的时候就只用拷贝指针了
    reus
        8
    reus  
       2019-12-12 16:37:54 +08:00
    注释里写了啊,os specific

    你写的 type file ... 只是 unix 的,windows 有不同的定义,plan9 也有不同的定义
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5382 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 07:35 · PVG 15:35 · LAX 00:35 · JFK 03:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.