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

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

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-12-10 09:52:352434browse

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!

Statement:
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
Previous article:What is golang assertion?Next article:What is golang assertion?