dongyong5912 2017-08-25 16:40
浏览 30
已采纳

避免在go包和结构名称中卡住的方法?

I have been doing a bit of go programming of late and while trying to follow Effective Go style guidelines, I sometimes find it difficult to avoid stuttering when naming packages and interfaces and structs.

As an example.
I might have a console package with a Console.go file containing a Console interface a console struct and a New function.

//console/Console.go
package console

type Console interface {
   Print(s String)
}

type console struct {
  ....
}

func (c *console) Print(s String){
  ....
}

func New() Console{
   return &console{}
}

Now when I use this somewhere I end up using a console.Console type everywhere.

When I have two or more structs in a package I end up things like con := console.NewConsole()

I don't mind having large mostly flat package structures but I do like to keep my code organized as much as possible. I am ok with the idea of IO.Reader and IO.Writer but what to do when the package is the same as the thing but still needs to be separated. (Yes I am aware that the given example could be Console.Writer but lets pretend its something completely different)

So my questions are: Is this stutter effect something I should even worry about? (ie. Is it bad form?) Does anyone have any tips in avoiding it?

  • 写回答

2条回答 默认 最新

  • du131642 2017-08-25 16:44
    关注

    Stuttering type names are generally fine - it's not unusual to have a foo.Foo, because package foo is dedicated to defining type Foo. There's absolutely nothing wrong with that.

    What you want to avoid is unnecessary stuttering; this would be things like foo.NewFoo when simply foo.New is sufficiently precise, or foo.FooBar and foo.FooBaz where foo.Bar and foo.Baz would work just as well.

    Consider the standard library's html/template, which defines a type (template.Template) and a constructor (template.New).

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

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题