Home > Backend Development > Golang > How to generate random elements from list in Golang?

How to generate random elements from list in Golang?

WBOY
Release: 2024-06-05 16:28:01
Original
1060 people have browsed it

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.

如何在 Golang 中从列表中生成随机元素?

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

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

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!

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