Advanced Golang

Modules Packages and Imports

Package name collision

When importing packages in Go, you may encounter a scenario where two packages share the same name. This is common when you need to use both the cryptographic random package and the mathematical random package, which are both named "rand." In this guide, you'll learn how to resolve such naming collisions by aliasing one of the packages.

Scenario Overview

In our example, we work with two packages:

  • crypto/rand: Provides cryptographically secure random number generation.
  • math/rand: Offers pseudo-random number generation.

Because both packages are named "rand," importing them directly would cause a naming collision. To prevent this conflict, you can assign an alias to one of the packages. In this article, we alias the "crypto/rand" package as crand, while leaving "math/rand" with its default name.

Example Code

Below is an example of how to alias the "crypto/rand" package and use both packages effectively:

import (
    crand "crypto/rand"
    "encoding/binary"
    "math/rand"
)

func seedRand() *rand.Rand {
    var b [8]byte
    _, err := crand.Read(b[:])
    if err != nil {
        panic("cannot seed with cryptographic random number generator")
    }
    r := rand.New(rand.NewSource(int64(binary.LittleEndian.Uint64(b[:]))))
    return r
}

Code Explanation

  • Aliasing to Avoid Conflict:
    The crypto/rand package is aliased as crand. This prevents confusion with the math/rand package.

  • Generating a Cryptographic Seed:
    The seedRand function utilizes crand.Read to generate 8 bytes of secure random data.

  • Seed Conversion:
    The generated bytes are converted into an int64 seed using binary.LittleEndian.Uint64.

  • Creating a Pseudo-Random Generator:
    Finally, a new pseudo-random generator is initialized using rand.New with the secure seed.

Note

Aliasing is a powerful feature when working with multiple packages that have overlapping names. It ensures your code remains clear and unambiguous while leveraging the strengths of different packages.

Conclusion

This technique of aliasing proves invaluable when working with packages that share the same identifier. By assigning an alias such as crand to the cryptographic random package, you can seamlessly use functions from both crypto/rand and math/rand without any confusion.

Well, that's it for this lesson. We'll see you in the next article.

Watch Video

Watch video content

Previous
Package comments and godoc