Programming Language: Golang

Namespace/Package Name: math/rand

Class/Type: Rand

Method/Function: Int63n

Examples at hotexamples.com: 19

The `math/rand` package in Go is used for generating random numbers. One of the functions provided in this package is `Rand.Int63n`, which generates a non-negative 63-bit integer in the range [0, n). Here are a few examples of how this function can be used:

**Example 1:** Generate a random number between 0 and 10^6

**Example 2:** Generate a random index for a slice of strings

**Example 1**, we set this to `1e6` to get a number between 0 and 10^6. In **Example 2**, we set it to the length of the `names` slice to get a random index to access a random name.

import ( "fmt" "math/rand" ) func main() { n := int64(1e6) rand.Seed(time.Now().UnixNano()) num := rand.Int63n(n) fmt.Println(num) }

import ( "fmt" "math/rand" "time" ) func main() { names := []string{"Alice", "Bob", "Charlie", "Dave"} rand.Seed(time.Now().UnixNano()) index := rand.Int63n(int64(len(names))) fmt.Println(names[index]) }In both examples, we need to call `rand.Seed` to initialize the random number generator with a unique seed value. This ensures that we get different random numbers each time we run the program. The range of the generated numbers is determined by the parameter passed to `Int63n`. In

Frequently Used Methods

Frequently Used Methods

Related

Related in langs