Skip to main content
Sometimes you need to import two packages that declare the same package name. A common example in Go is when both the crypto module and the math module provide packages named rand. This causes a name collision that you can resolve by assigning a local alias to one of the imports. Below is a concise, real-world example: we alias crypto/rand as crand so it doesn’t collide with math/rand. The example seeds a new math/rand.Rand using cryptographic randomness from crypto/rand.
Use a package alias when two imports share the same package name to avoid name collisions and make it clear which package you mean.
Explanation
  • crand "crypto/rand" gives the crypto/rand package the local name crand, preventing a collision with math/rand.
  • crand.Read fills an 8-byte array with cryptographically secure random bytes.
  • binary.LittleEndian.Uint64(b[:]) converts those bytes to a 64-bit unsigned integer; casting to int64 makes it suitable for rand.NewSource.
  • rand.New returns a *rand.Rand seeded with the secure value. Use this returned instance (r) to call pseudo-random functions like r.Intn(100).
Quick usage example
When to use aliases (and naming tips)
  • Use an alias when two packages have the same base name (e.g., rand).
  • Prefer short, descriptive aliases that make intent obvious — e.g., crand for crypto/rand.
  • Avoid unnecessary aliases for a single import; they add cognitive overhead if the package name is already clear.
Summary table
Avoid overusing aliases — only introduce them when they resolve a real ambiguity or significantly improve readability. Poorly chosen aliases can make code harder to understand.
Links and references That’s it for this lesson.

Watch Video