17

文件或目录的常用变量名称是“路径”。不幸的是,这也是 Go 中一个包的名称。此外,将路径更改为 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)
4

2 回答 2

12

path string正在遮蔽导入的path. 您可以做的是通过将行更改为来将导入包的别名设置为例如 pathpkg "path"import因此pathpkg "path"代码的开头如下所示

package main

import (
    pathpkg "path"
    "os"
)

当然,您必须将DoIt代码更改为:

pathpkg.Join(os.TempDir(), path)
于 2011-10-14T19:03:55.500 回答
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)
}
于 2011-10-15T08:07:31.840 回答