可能有一个New函数在Golang中分配文件描述符

As I come from a C and C++ background and golang is semantically different I have some discussions about function names "New" vs "Open" and what the programmer expects what to happen under the hood. I have created a package where the New function opens file descriptors to temporary files. I'm not sure this is intended behavior for APIs written in Go.

Here is a snippet:

// Not directly convenient New allocates file descriptors
deb := New()
deb.AddFile("/tmp/myfile")
deb.Write("/tmp/mypackage.deb")
deb.Close()

// Idiomatic it opens file descriptors but we have to provide context to open
info := &Props{Name: "mypackage"}
deb := info.Open("/tmp/mypackage.deb")
deb.AddFile("/tmp/myfile")
deb.Close()

Go's community is still finding its idioms and patterns, so don't consider anything dogma. Based on what I've seen in a year and a half, I don't think it's wrong to touch disk in a New function if it has godoc comments explaining the behavior. It would be unusual, and probably make more sense to touch the disk in d.Write(). Some common patterns I've seen with New functions:

  • are only exported when designed for use by other packages
  • makes sense when invoked from other packages with the package name prefixed: d := deb.New(...) (since you have a variable named deb, your package is something else)
  • returns an instance of the package's main business logic, to be used further
  • accept dependencies as arguments instead of constructing its own dependencies (hopefully any behavioral dependencies are interfaces)
  • often a main() function assembles those dependencies, calls d := deb.New(deps), and executes the behavior d.AddFile(); d.Write(); d.Close()

an example signature using an interface:

package deb

// New accepts blah returning a *Deb. It returns nil if blah.
func New(name string, to io.WriteCloser) *Deb {...}