20

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)
Nate
  • 5,237
  • 7
  • 42
  • 52

2 Answers2

14

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)
macbirdie
  • 16,086
  • 6
  • 47
  • 54
  • 3
    I was afraid that would be the answer...Wish there was another way, but I'm not seeing it. – Nate Oct 14 '11 at 19:14
  • 1
    You know what is kind of ironic? The path package code doesn't have this limitation. If you take a look at path.Split (http://golang.org/src/pkg/path/path.go?s=2665:2707#L97), you'll see it has an argument named path. path is defined in the file, but not imported... – Nate Oct 14 '11 at 19:20
  • 3
    This limitation doesn't apply there, because there's no package `path` imported and no other `path` variable to shadow, but I can assume you already know that. ;) – macbirdie Oct 14 '11 at 19:41
  • Yep, I understand why, but found it kind of funny...oh well, I guess we have to deal with the limitation. – Nate Oct 16 '11 at 18:36
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)
}
jnml
  • 35
  • 1