英文:
May a New function allocate filedescriptors in Golang
问题
由于我是一个中文翻译助手,我将为您翻译以下内容:
由于我来自C和C++的背景,而golang在语义上有所不同,所以我对函数名称“New”与“Open”有一些讨论,以及程序员对底层操作的期望。我创建了一个包,其中的New函数打开了临时文件的文件描述符。我不确定这是否是Go语言中API的预期行为。
以下是代码片段:
// 直接使用New不太方便,它会分配文件描述符
deb := New()
deb.AddFile("/tmp/myfile")
deb.Write("/tmp/mypackage.deb")
deb.Close()
// 惯用法是它打开文件描述符,但我们需要提供上下文来打开
info := &Props{Name: "mypackage"}
deb := info.Open("/tmp/mypackage.deb")
deb.AddFile("/tmp/myfile")
deb.Close()
希望对您有所帮助!
英文:
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:
<!-- language: lang-golang -->
// 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
得分: 2
Go的社区仍在寻找其惯用语和模式,所以不要认为任何东西都是教条。根据我在一年半的时间里所见,如果在New
函数中有godoc注释解释其行为,我认为在函数中涉及磁盘操作并不是错误的。这可能是不寻常的,可能更合理的做法是在d.Write()
中涉及磁盘操作。我见过一些常见的New
函数模式:
- 只有在设计供其他包使用时才会导出
- 当从其他包中调用时,使用包名前缀是有意义的:
d := deb.New(...)
(由于你有一个名为deb
的变量,你的包可能是其他东西) - 返回包的主要业务逻辑的实例,以供进一步使用
- 将依赖项作为参数接受,而不是构建自己的依赖项(希望任何行为依赖项都是接口)
- 通常一个
main()
函数组装这些依赖项,调用d := deb.New(deps)
,并执行行为d.AddFile(); d.Write(); d.Close()
使用接口的示例签名:
package deb
// New接受blah并返回*Deb。如果blah,则返回nil。
func New(name string, to io.WriteCloser) *Deb {...}
英文:
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 nameddeb
, 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, callsd := deb.New(deps)
, and executes the behaviord.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 {...}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论