golang File struct is like this:
type File struct{
*file
}
and File struct functiona is also design to recive a pointer,why it design like this?
golang File struct is like this:
type File struct{
*file
}
and File struct functiona is also design to recive a pointer,why it design like this?
It is explained in the Go os package source code comments.
For example, this is safe:
package main
import "os"
func main() {
f, err := os.Create("/tmp/atestfile")
if err != nil {
*f = os.File{}
}
// finalizer runs
}
Package os
go/src/os/types.go: // File represents an open file descriptor. type File struct { *file // os specific } go/src/os/file_plan9.go: // file is the real representation of *File. // The extra level of indirection ensures that no clients of os // can overwrite this data, which could cause the finalizer // to close the wrong file descriptor. type file struct { fd int name string dirinfo *dirInfo // nil unless directory being read } go/src/os/file_unix.go: // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris // file is the real representation of *File. // The extra level of indirection ensures that no clients of os // can overwrite this data, which could cause the finalizer // to close the wrong file descriptor. type file struct { pfd poll.FD name string dirinfo *dirInfo // nil unless directory being read nonblock bool // whether we set nonblocking mode } go/src/os/file_windows.go: // file is the real representation of *File. // The extra level of indirection ensures that no clients of os // can overwrite this data, which could cause the finalizer // to close the wrong file descriptor. type file struct { pfd poll.FD name string dirinfo *dirInfo // nil unless directory being read }