Home > Backend Development > Golang > How many ways are there to generate random numbers in golang?

How many ways are there to generate random numbers in golang?

爱喝马黛茶的安东尼
Release: 2019-12-10 09:52:35
Original
2469 people have browsed it

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)
}
Copy after login

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)
}
Copy after login

Method 3: Similar to Method 1

func main(){
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    n := r.Intn(3000)
    fmt.Println(n)
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template