Disambiguate package name from local var in Go

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

Disambiguate package name from local var in Go

问题

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

import "path"

func foo() {
    path := "/some/path"
    // 在这里进行区分
    path.Join(path, "/some/other/path")
}
英文:

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...

import "path"

func foo() {
    path := "/some/path"
    // Disambiguate here
    path.Join(path, "/some/other/path")
}

答案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链接):

join := path.Join

path := "/some/path"
path = join("/some/other/path")

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

type Path string

func (p Path) Join(elem ...string) string {
    return path.Join(append([]string{string(p)}, elem...)...)
}

fmt.Println("Hello, playground")

path := "/some/path"

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):

join := path.Join

path := "/some/path"
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):

type Path string

func (p Path) Join(elem ...string) string {
	return path.Join(append([]string{string(p)}, elem...)...)
}

fmt.Println("Hello, playground")

path := "/some/path"

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:

确定