Home > Article > Backend Development > How many ways are there to generate random numbers in golang?
There are many ways to generate random numbers. Here is a summary, so you can choose the appropriate one.
Method 1: Set the seed to generate a random number between 0-30000
func main(){ rand.Seed(time.Now().UnixNano()) num := rand.Intn(30000) fmt.Println(num) }
Method 2: Generate a random number in the specified interval
func RandInt(min, max int) int { if min >= max || min == 0 || max == 0 { return max } return rand.Intn(max-min) + min } //调用 func main(){ num := RandInt(3,200) fmt.Println(num) }
Method 3: Similar to Method 1
func main(){ r := rand.New(rand.NewSource(time.Now().UnixNano())) n := r.Intn(3000) fmt.Println(n) }
PHP Chinese website, there are a large number of free Golang introductory tutorials, everyone is welcome to learn!
The above is the detailed content of How many ways are there to generate random numbers in golang?. For more information, please follow other related articles on the PHP Chinese website!