English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Functions & Methods

Golang Structs

Golang Slices & Arrays

Golang Strings (String)

Golang Pointers

Golang Interfaces

Golang Concurrency

Golang Exceptions (Error)

Golang Miscellaneous

Go Language Generate Random Number (rand)

We can use the rand object to generate random numbers. We should provide some seeds for the rand object to make the generated numbers different. If we do not provide a seed, the compiler will always produce the same result.

Random Number Generation

package main
import "fmt"
import (
	"math/rand
	//"time"
	"time"
)
func main() {
	fmt.Print(rand.Intn(100))  //will produce 0 to100 between random integers
	fmt.Println()
	fmt.Print(rand.Float64())	//will produce 0 to1Random numbers between
	fmt.Println()
	rand.Seed(time.Now().Unix())  //Random numbers generated by Seed
	myrand := random(1, 20)
	fmt.Println(myrand)
}
func random(min, max int) int {
	return rand.Intn(max - min) + min
}

Output:

81
0.9405090880450124
17