Skip to Content
Course content

185: math/rand vs math/rand/v2

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I often see developers assume that math/rand/v2 is just a "version update" in the way a library might go from 1.1 to 1.2. They think they can just swap the import path and everything will work the same, only slightly faster. That's a dangerous assumption because v2 isn't a patch; it's a redesign that fixes several architectural mistakes we've had to live with in Go for over a decade.

Thinking v2 is a drop-in replacement

If you try to just change your import and run your code, your compiler is going to yell at you immediately. The most visible change is the naming convention. In v1, we had rand.Intn(). In v2, it's rand.IntN(). It seems like a trivial change—just a capital 'N'—but it's part of a larger effort to make the API consistent with the rest of the Go standard library.

// This works in v1, but fails in v2
import "math/rand"
val := rand.Intn(100) 

// This is the v2 way
import "math/rand/v2"
val := rand.IntN(100)

But the real issue isn't the capitalization. It's the behavior of the global generator. In v1, the global functions are protected by a mutex. If you have a high-concurrency application—say, a load balancer assigning random weights to thousands of requests per second—all those goroutines are fighting over a single lock. I've seen production apps crawl to a halt because of contention in math/rand.

Moving past the global seed ritual

For years, the first thing every Go developer wrote was rand.Seed(time.Now().UnixNano()). If you forgot it, your "random" numbers were the same every time you restarted the app. It was a boilerplate tax we all paid.

In v2, that ritual is dead. The global generator is now automatically seeded. You don't need to call a seed function just to get basic randomness. More importantly, v2 introduces ChaCha8, a much faster and more statistically sound algorithm than the old lagged Fibonacci generator used in v1. When I'm writing new services now, I don't even think about v1 unless I'm maintaining a legacy codebase.

Here is how the mental model shifts when you actually need a specific source of randomness (like for a reproducible test) in v2:

import "math/rand/v2"

func main() {
    // Instead of the old rand.NewSource(), we use NewPCG
    // PCG is a modern, efficient generator
    pcg := rand.NewPCG(1, 2) 
    r := rand.New(pcg)
    
    fmt.Println(r.IntN(100))
}

Notice NewPCG. The v1 Source interface was clunky and limited. The new PCG (Permuted Congruential Generator) is simply better. It's faster, has a longer period, and is easier to reason about. I'll be honest: the transition to v2 is one of the few times where the "breaking change" of a version bump is actually a gift to the developer.

  • Use math/rand/v2 for all new projects.
  • Stop using rand.Seed(); it's gone (and unnecessary).
  • Check your function calls: Intn is now IntN, Float64 stays the same, but the underlying engine is vastly improved.



📋 Practical Task

Refactoring a Random Session ID Generator to v2

You have a legacy function that generates a random session string. It currently uses math/rand (v1) and relies on the old Seed pattern. Your task is to refactor this to use math/rand/v2.

Requirements:

  • Replace the math/rand import with math/rand/v2.
  • Remove the call to rand.Seed() entirely.
  • Update the random integer generation to use the correct v2 function naming.
  • Ensure the function still produces a random string of 10 alphanumeric characters.
package main

import (
    "fmt"
    "math/rand" // Change this
    "time"
)

func init() {
    // Remove this logic
    rand.Seed(time.Now().UnixNano())
}

func generateSessionID() string {
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    b := make([]byte, 10)
    for i := range b {
        // Update this call to v2
        b[i] = charset[rand.Intn(len(charset))]
    }
    return string(b)
}

func main() {
    fmt.Println("Session ID:", generateSessionID())
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.