doushan7997 2017-09-07 06:25
浏览 34
已采纳

可能有一个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()
  • 写回答

1条回答 默认 最新

  • doudoulb1234 2017-09-07 07:20
    关注

    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 {...}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来