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。あなたができることは、行"path"をにimport変更することによって、インポートされたパッケージのエイリアスを例えばpathpkgに設定することです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 に答える