Disambiguate package name from local var in Go

huangapple go评论114阅读模式
英文:

Disambiguate package name from local var in Go

问题

有没有一种好的方法来区分包名和局部变量?如果不必要的话,我不想重构导入名称或变量名称。以这个例子为例...

  1. import "path"
  2. func foo() {
  3. path := "/some/path"
  4. // 在这里进行区分
  5. path.Join(path, "/some/other/path")
  6. }
英文:

Is there a good way to disambiguate between a package name and a local variable? I'd rather not refactor the import name or variable name if I don't have to. Take for example...

  1. import "path"
  2. func foo() {
  3. path := "/some/path"
  4. // Disambiguate here
  5. path.Join(path, "/some/other/path")
  6. }

答案1

得分: 10

本地变量在这里始终会覆盖(遮蔽)包。选择另一个变量名,或将包别名为其他名称:

http://play.golang.org/p/9ZaJa5Joca

或者

http://play.golang.org/p/U6hvtQU8dx

请参考其他答案中nemo的替代方案。我认为最可维护的方法是选择一个不会与包名重叠的变量名。

英文:

The local variable always overrides (shadows) the package here. Pick another variable name, or alias the package as something else:

http://play.golang.org/p/9ZaJa5Joca

or

http://play.golang.org/p/U6hvtQU8dx

See nemo's alternatives in the other answer. I think the most maintainable way is to pick a variable name that won't overlap with the package name.

答案2

得分: 6

我可以想到两个额外的选项:

  1. path.Join存储在一个变量中。
  2. path作为一个实现了Join方法的类型。

第一个选项很简单。你可以在声明path之前将path.Join存储在一个变量中,并在需要时调用它(play链接):

  1. join := path.Join
  2. path := "/some/path"
  3. path = join("/some/other/path")

第二个选项稍微复杂一些,我不认为你真的应该这样做,但这是一个可能性(play链接):

  1. type Path string
  2. func (p Path) Join(elem ...string) string {
  3. return path.Join(append([]string{string(p)}, elem...)...)
  4. }
  5. fmt.Println("Hello, playground")
  6. path := "/some/path"
  7. path = Path(path).Join("/some/other/path")
英文:

There are two additional options I can think of:

  1. store path.Join in a variable
  2. make path a type that implements Join

The first is simple. Instead of path.Join you store path.Join in a variable before declaring path and call it instead (play):

  1. join := path.Join
  2. path := "/some/path"
  3. path = join("/some/other/path")

The second is a bit more complicated and I don't think you should actually do that but it is a possibility
(play):

  1. type Path string
  2. func (p Path) Join(elem ...string) string {
  3. return path.Join(append([]string{string(p)}, elem...)...)
  4. }
  5. fmt.Println("Hello, playground")
  6. path := "/some/path"
  7. path = Path(path).Join("/some/other/path")

huangapple
  • 本文由 发表于 2013年12月21日 11:19:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/20715049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定