Home > Article > Backend Development > How to generate random elements from list in Golang?
How to generate random elements of a list in Golang: use rand.Intn(len(list)) to generate a random integer within the length range of the list; use the integer as an index to get the corresponding element from the list.
#How to generate random elements from a list in Golang?
In Golang, you can use the built-in rand
package to generate a random integer in a range, and then use this integer to index the list and get a random element.
The following is the code on how to implement it:
package main import ( "fmt" "math/rand" "time" ) func main() { // 创建一个元素列表 list := []string{"a", "b", "c", "d", "e"} // 设置随机种子(通常使用当前时间作为种子) rand.Seed(time.Now().UnixNano()) // 生成一个范围内的随机整数,范围为 [0, len(list)-1] n := rand.Intn(len(list)) // 使用随机整数作为索引,从列表中获取随机元素 randomElement := list[n] fmt.Println(randomElement) }
Practical case:
The following is an example showing how to use the above code in a program to generate a Random number:
package main import ( "fmt" "math/rand" "time" ) func main() { numbers := []int{1, 2, 3, 4, 5} // 生成一个随机索引 randomIndex := rand.Intn(len(numbers)) // 获取随机数字 randomNumber := numbers[randomIndex] fmt.Println(randomNumber) }
Running this program will output a number randomly selected from the list.
The above is the detailed content of How to generate random elements from list in Golang?. For more information, please follow other related articles on the PHP Chinese website!