Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disambiguate package name from local var in Go

Tags:

package

go

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")
}
like image 661
Lander Avatar asked Dec 21 '13 03:12

Lander


People also ask

How to name packages in golang?

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.

How do you name variables in Go?

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.

What does it mean by package name?

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.

What is package scope in Golang?

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.


2 Answers

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.

like image 156
Eve Freeman Avatar answered Oct 20 '22 19:10

Eve Freeman


There are two additional options I can think of:

  1. store path.Join in a variable
  2. make path 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")
like image 23
nemo Avatar answered Oct 20 '22 19:10

nemo