Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to generate random numbers in Go language

Shubham Singh Kshatriya

Overview

The Go language provides a built-in package named math/rand for generating pseudo-random numbers.

Pseudo-random numbers are a deterministic sequence that depends on a seed value. To generate random numbers on every execution, we need to set the seed every time.

In this shot, we will use the math/rand package to generate a random number.

Syntax

rand.Int()

rand.Intn(n)

rand.Float64() 
  • rand.Int(): Returns a random integer.
  • rand.Intn(n): Accepts one argument, n (the upper bound), and will throw an error if the value of n is less than zero. rand.Intn(n) returns a random integer between 0 and n.
  • rand.Float64(): Returns a random float64 number between 0.0 and 1.0.

Example

package main

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

func main() {
  // seed to get different result every time
  rand.Seed(time.Now().UnixNano())
  
  fmt.Println(rand.Int())
  fmt.Println(rand.Int())
  fmt.Println(rand.Int())
  fmt.Println()
  fmt.Println(rand.Intn(50))
  fmt.Println(rand.Intn(50))
  fmt.Println(rand.Intn(50))
  fmt.Println()
  fmt.Println(rand.Float64())
  fmt.Println(rand.Float64())
  fmt.Println(rand.Float64())
}
Random Number Generation

RELATED TAGS

golang
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring