How does one use a variable name with the same name as a package in Go?

偶尔善良 提交于 2021-02-18 20:32:12

问题


A common variable name for files or directories is "path". Unfortunately that is also the name of a package in Go. Besides, changing path as a argument name in DoIt, how do I get this code to compile?

package main

import (
    "path"
    "os"
)

func main() {
    DoIt("file.txt")
}

func DoIt(path string) {
    path.Join(os.TempDir(), path)
}

The error I get is:

$6g pathvar.go 
pathvar.go:4: imported and not used: path
pathvar.go:13: path.Join undefined (type string has no field or method Join)

回答1:


The path string is shadowing the imported path. What you can do is set imported package's alias to e.g. pathpkg by changing the line "path" in import into pathpkg "path", so the start of your code goes like this

package main

import (
    pathpkg "path"
    "os"
)

Of course then you have to change the DoIt code into:

pathpkg.Join(os.TempDir(), path)



回答2:


package main

import (
    "path"
    "os"
)

func main() {
    DoIt("file.txt")
}

// Just don't introduce a same named thing in the scope
// where you need to use the package qualifier.
func DoIt(pth string) {
    path.Join(os.TempDir(), pth)
}


来源:https://stackoverflow.com/questions/7772229/how-does-one-use-a-variable-name-with-the-same-name-as-a-package-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!