Developer Tools for Random Data Generation // v2.5.1
root@generate-random:~/numbers/go$ _

Generate Random Numbers in Go

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Go

What: Generate random numbers in Go using <code>math/rand</code> for general purposes or <code>crypto/rand</code> for cryptographically secure random numbers in Go applications.

Try it: Use our interactive Numbers generator or integrate this code into your Go application.

Generate random numbers in Go using math/rand for general purposes or crypto/rand for cryptographically secure random numbers in Go applications. Looking for other languages? Check our code examples in PHP , JavaScript , Python , Java , C# , C++ and Ruby or use our interactive web generator.

Go Code Example

package main

import (
    "crypto/rand"
    "fmt"
    "math/big"
    "math/rand/v2"
)

func main() {
    // Generate a single random number between 1 and 100
    randomNumber := rand.IntN(100) + 1
    fmt.Println(randomNumber)  // Example output: 42

    // Generate multiple random numbers
    numbers := make([]int, 10)
    for i := range numbers {
        numbers[i] = rand.IntN(100) + 1
    }
    fmt.Println(numbers)
    // Example output: [23 7 91 45 12 68 3 89 54 31]

    // Generate cryptographically secure random number
    nBig, _ := rand.Int(rand.Reader, big.NewInt(100))
    secureNumber := nBig.Int64() + 1
    fmt.Println(secureNumber)  // Example: 67

    // Random float between 0 and 100
    randomFloat := rand.Float64() * 100
    fmt.Printf("%.2f\n", randomFloat)  // Example: 42.17
}

[EXPLANATION]

Go v2 (Go 1.22+) uses math/rand/v2 with auto-seeding. rand.IntN(n) generates integers from 0 to n-1. For cryptographic security, use crypto/rand which provides cryptographically secure random bytes.

Expected Output

42
[23 7 91 45 12 68 3 89 54 31]
67
42.17

Common Use Cases

  • Microservices and backend API development
  • Cloud-native applications (Kubernetes, Docker)
  • Concurrent systems requiring thread-safe randoms
  • Security token and session ID generation
  • CLI tools and system utilities
  • High-performance network services

Important Notes

  • Go 1.22+ auto-seeds math/rand/v2 - no manual seeding needed
  • Use crypto/rand for security-critical applications
  • math/rand is safe for concurrent use
  • Older Go versions use math/rand (v1) and require seeding

Try Our Interactive Generator

Don't want to write code? Use our free web-based Numbers generator with instant results.

TRY NUMBERS GENERATOR →