Is there a good way to disambiguate between a package name and a local variable? I'd rather not refactor the import name or variable name if I don't have to. Take for example...
import "path"
func foo() {
path := "/some/path"
// Disambiguate here
path.Join(path, "/some/other/path")
}
Package names should be lowercase. Don't use snake_case or camelCase in package names. The Go blog has a comprehensive guide about naming packages with a good variety of examples.
The naming of variables is quite flexible, but there are some rules to keep in mind: Variable names must only be one word (as in no spaces). Variable names must be made up of only letters, numbers, and underscores ( _ ). Variable names cannot begin with a number.
The package name of an Android app uniquely identifies your app on the device, in Google Play Store, and in supported third-party Android stores.
Visibility in this context means the file space from which a package or other construct can be referenced. For example, if we define a variable in a function, the visibility (scope) of that variable is only within the function in which it was defined.
The local variable always overrides (shadows) the package here. Pick another variable name, or alias the package as something else:
http://play.golang.org/p/9ZaJa5Joca
or
http://play.golang.org/p/U6hvtQU8dx
See nemo's alternatives in the other answer. I think the most maintainable way is to pick a variable name that won't overlap with the package name.
There are two additional options I can think of:
path.Join
in a variablepath
a type that implements Join
The first is simple. Instead of path.Join
you store path.Join
in a variable before declaring path
and call it instead (play):
join := path.Join
path := "/some/path"
path = join("/some/other/path")
The second is a bit more complicated and I don't think you should actually do that but it is a possibility (play):
type Path string
func (p Path) Join(elem ...string) string {
return path.Join(append([]string{string(p)}, elem...)...)
}
fmt.Println("Hello, playground")
path := "/some/path"
path = Path(path).Join("/some/other/path")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With