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.
crand "crypto/rand"gives thecrypto/randpackage the local namecrand, preventing a collision withmath/rand.crand.Readfills an 8-byte array with cryptographically secure random bytes.binary.LittleEndian.Uint64(b[:])converts those bytes to a 64-bit unsigned integer; casting toint64makes it suitable forrand.NewSource.rand.Newreturns a*rand.Randseeded with the secure value. Use this returned instance (r) to call pseudo-random functions liker.Intn(100).
- Use an alias when two packages have the same base name (e.g.,
rand). - Prefer short, descriptive aliases that make intent obvious — e.g.,
crandforcrypto/rand. - Avoid unnecessary aliases for a single import; they add cognitive overhead if the package name is already clear.
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.
- Go packages: https://pkg.go.dev/std
crypto/rand: https://pkg.go.dev/crypto/randmath/rand: https://pkg.go.dev/math/randencoding/binary: https://pkg.go.dev/encoding/binary- Effective Go — package names and conventions: https://go.dev/doc/effective_go