The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
yujianwjj

GO os.File 的疑问

  •  
  •   yujianwjj · Dec 12, 2019 · 4456 views
    This topic created in 2543 days ago, the information mentioned may be changed or developed.

    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 replies  •  2019-12-12 16:37:54 +08:00
    ArJun
    ArJun
    Dec 12, 2019
    1
    面向对象开发
    airfling
    airfling
    Dec 12, 2019
    2
    小写的是私有属性,类似于 java 中 private,对外暴露的是方法和构造方法都是依靠指针操作,防止外人通过反射修改吧
    magua
    magua
    Dec 12, 2019
    3
    私有化,可以防止外部修改 file 结构体的值。
    codehz
    codehz
    Dec 12, 2019 via Android
    4
    原因已经在注释里了:os specific
    不同操作系统的文件结构体可能不同,导致结构体大小也不一致,加一个间接指针以后,大小就确定了。
    heimeil
    heimeil
    Dec 12, 2019
    5
    file.go
    file_plan9.go
    file_posix.go
    file_unix.go
    file_windows.go

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

    你写的 type file ... 只是 unix 的,windows 有不同的定义,plan9 也有不同的定义
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1923 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 12:08 · PVG 20:08 · LAX 04:08 · JFK 07:08
    ♥ Do have faith in what you're doing.