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

The common variable name for files or directories is "path". Unfortunately, this is also the name of the package in Go. Also, changing the path as an 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) 
+7
source share
2 answers

path string hides the imported path . What you can do is set the imported package alias, for example. pathpkg by changing the line "path" in import to pathpkg "path" , so the beginning of your code will look like this

 package main import ( pathpkg "path" "os" ) 

Of course you should change the DoIt code to:

 pathpkg.Join(os.TempDir(), path) 
+9
source
 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) } 
0
source

All Articles