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

GO os.File 的疑问

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

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

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