英文:
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
我可以想到两个额外的选项:
- 将
path.Join
存储在一个变量中。 - 将
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:
- store
path.Join
in a variable - make
path
a type that implementsJoin
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论