dongzhuo6137 2013-02-22 04:01
浏览 37
已采纳

在go中使用静态类型构造函数有什么明显的缺点?

I've always found the package.New() syntax in go rather awkward to work with.

The suggestion is that if a package holds only a single type, using package.New() to create an instance; if multiple types exist, using package.NewBlah(). http://golang.org/doc/effective_go.html#package-names

However, this approach falls down if you if you have an existing package with a New() api, adding a new external type to the package breaks the api, because you must now rename this NewFoo(). Now you have to go and change anything that uses New(), which is deeply irritating.

...and I'm just discontent with the aesthetic of writing this:

import "other"
import "bar"
import "foo"

o := other.New()  // <-- Weird, what type am I getting? No idea.
x := bar.New()  
y := foo.NewFoo() // <-- Awkward, makes constructor naming look inconsistent   
z := foo.NewBar() 

So, recently I've been using this pattern instead:

x := foo.Foo{}.New()   // <-- Immediately obvious I'm getting a Foo
y := foo.Bar{}.New()   // <-- Only an additional 3 characters on NewBar{}
o := other.Foo{}.New() // <-- Consistent across all packages, no breakage on update

Where the module is defined something like this:

package foo

type Foo struct {
  x int
}

func (s Foo) New() *Foo {
  // Normal init stuff here
  return &s // <-- Edit: notice the single instance is returned 
}

type Bar struct {
}

func (Bar) New() *Bar {
  return &Bar{} // <-- Edit: Bad, results in double alloc. Not like this. 
}

Godoc seems to work fine with it, and it seems more obvious and consistent to me, without additional verbosity.

So, question: Is there any tangible downside to this?

  • 写回答

2条回答 默认 最新

  • duan7772 2013-02-22 04:25
    关注

    Yes, it has a downside. This approach may generate unnecessary garbage - depending on how good the optimization of a specific Go compiler implementation is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?