如何在Go中使用与包名相同的变量名?

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

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

huangapple
  • 本文由 发表于 2011年10月15日 02:54:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/7772229.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定