2013-12-21 03:19



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")
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doudi8231 doudi8231 8年前

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




    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.

    点赞 评论 复制链接分享
  • doutan1905 doutan1905 8年前

    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")
    点赞 评论 复制链接分享