跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • GO os.File 的疑问
未分類
10 1 月 2020

GO os.File 的疑问

GO os.File 的疑问

資深大佬 : yujianwjj 64

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)

  • 資深大佬 : ArJun

    面向对象开发

  • 資深大佬 : airfling

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

  • 資深大佬 : magua

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

  • 資深大佬 : codehz

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

  • 資深大佬 : heimeil

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

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

  • 主 資深大佬 : yujianwjj

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

  • 資深大佬 : monsterxx03

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

  • 資深大佬 : reus

    注释里写了啊,os specific

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

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具