DEV Community

Cover image for To the point - generating random numbers in golang
HM
HM

Posted on

3 1

To the point - generating random numbers in golang

Generating random numbers

(integers for the sake of this post)

Usually

Most commonly, you would use the math/rand and the time pkg to seed the rand generator in go. This is shown below:

// code#1
package main

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

func main() {
    rand.Seed(time.Now().UnixNano())
    x := rand.Intn(5) // An int between [0,5)
    fmt.Println(x)
}
Enter fullscreen mode Exit fullscreen mode

Unusually

Most of times, code#1 will do the job, BUT what if your randomness cannot depend on time alone.

Problem

As an example, suppose you want to create a function that must return two random numbers between 0 and n

Thought 1

You could math/rand.Perm(n) seeded with time.Now().UnixNano() to obtain a slice of n integers. And then pick the first two. Something like:

//code#2

func main() {
    rand.Seed(time.Now().UnixNano())
    x := rand.Perm(5)
    fmt.Println(x[0], x[1])
}
Enter fullscreen mode Exit fullscreen mode

BUT, this is highly inefficient especially for large values of n.

Thought 2

Make use of the crypto/rand package to generate a truly random int.
Something like:

// code#3
package main

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

func main() {
    x, _ := rand.Int(rand.Reader, big.NewInt(5))
    y, _ := rand.Int(rand.Reader, big.NewInt(5))
    fmt.Println(x, y)
}
Enter fullscreen mode Exit fullscreen mode

That's all! Happy randomizing!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay