Search code examples
gopackagenames

Go library package names


I have some questions on package naming for external Go libraries.

I am interested if using generic names like "text" is considered a good practice? Having in mind that I cannot declare a "nested package" and that the library I am building deals with text processing, is it ok to have the package named "text" or should I stick to the library name as a package name too?

I am building a set of libraries (different projects) and I want to combine them under the same package. Is this also problematic? I am new to the Go community and am still not sure if package pollution is a problem or not (I do not see a problem as long as I import few packages in my code).


Solution

  • The reference on that naming topic is "blog: Package names"

    It includes:

    Avoid unnecessary package name collisions.
    While packages in different directories may have the same name, packages that are frequently used together should have distinct names. This reduces confusion and the need for local renaming in client code. For the same reason, avoid using the same name as popular standard packages like io or http.

    Check also your package publishing practice, as it will help disambiguate your "text" package from others.

    As illustrated in "An Introduction to Programming in Go / Packages":

    math is the name of a package that is part of Go's standard distribution, but since Go packages can be hierarchical we are safe to use the same name for our package. (The real math package is just math, ours is golang-book/chapter11/math)

    When we import our math library we use its full name (import "golang-book/chapter11/math"), but inside of the math.go file we only use the last part of the name (package math).

    We also only use the short name math when we reference functions from our library. If we wanted to use both libraries in the same program Go allows us to use an alias:

    import m "golang-book/chapter11/math"
    
    func main() {
      xs := []float64{1,2,3,4}
      avg := m.Average(xs)
      fmt.Println(avg)
    }
    

    m is the alias.


    As mentioned in the comments by elithrar, Dave Cheney has some additional tips:

    In other languages it is quite common to ensure your package has a unique namespace by prefixing it with your company name, say com.sun.misc.Unsafe.
    If everyone only writes packages corresponding to domains that they control, then there is little possibility of a collision.

    In Go, the convention is to include the location of the source code in the package’s import path, ie

    $GOPATH/src/github.com/golang/glog
    

    This is not required by the language, it is just a feature of go get.