英文:
How does one use a variable name with the same name as a package in Go?
问题
一个常见的文件或目录的变量名是"path"。不幸的是,这也是Go语言中的一个包的名称。除了将path作为DoIt函数的参数名进行更改之外,我该如何使这段代码编译通过?
package main
import (
"path"
"os"
)
func main() {
DoIt("file.txt")
}
func DoIt(path string) {
path.Join(os.TempDir(), path)
}
我得到的错误是:
$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)
英文:
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
得分: 14
path string正在遮蔽导入的path。你可以通过将导入包的别名设置为pathpkg,将import中的"path"改为pathpkg "path",这样你的代码开头就会像这样:
package main
import (
pathpkg "path"
"os"
)
当然,然后你需要将DoIt代码改为:
pathpkg.Join(os.TempDir(), path)
英文:
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
得分: 1
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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论