Home > Backend Development > Golang > How to generate random numbers in golang

How to generate random numbers in golang

silencement
Release: 2019-12-25 14:23:49
Original
3004 people have browsed it

How to generate random numbers in golang

Generate random numbers in the interval

func RandInt(min, max int) int {
    if min >= max || min == 0 || max == 0 {
        return max
    }
    return rand.Intn(max-min) + min}
Copy after login

Generate random numbers in the specified interval (including pure numbers/pure letters/random)

const (
    KC_RAND_KIND_NUM   = 0  // 纯数字
    KC_RAND_KIND_LOWER = 1  // 小写字母
    KC_RAND_KIND_UPPER = 2  // 大写字母
    KC_RAND_KIND_ALL   = 3  // 数字、大小写字母)// 随机字符串func Krand(size int, kind int) []byte {
    ikind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size)
    is_all := kind > 2 || kind < 0
    rand.Seed(time.Now().UnixNano())
    for i :=0; i < size; i++ {
        if is_all { // random ikind
            ikind = rand.Intn(3)
        }
        scope, base := kinds[ikind][0], kinds[ikind][1]
        result[i] = uint8(base+rand.Intn(scope))
    }
    return result}
Copy after login

Recommended learning "golang tutorial

The above is the detailed content of How 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