How does one use a variable name with the same name as a package in Go?
Asked Answered
B

2

21

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)
Boden answered 14/10, 2011 at 18:54 Comment(0)
T
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)
Twine answered 14/10, 2011 at 19:3 Comment(4)
I was afraid that would be the answer...Wish there was another way, but I'm not seeing it.Boden
You know what is kind of ironic? The path package code doesn't have this limitation. If you take a look at path.Split (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...Boden
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. ;)Twine
Yep, I understand why, but found it kind of funny...oh well, I guess we have to deal with the limitation.Boden
S
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)
}
Samuelsamuela answered 15/10, 2011 at 8:7 Comment(2)
Yep, that is the obvious way to do it. I was just wondering if there was another way...Boden
Of course it was not what OP meant. Your answer is totally irrelevant.Fairing

© 2022 - 2024 — McMap. All rights reserved.