0xBF
0xBF

0xBF

Go Cheatsheet - Random

0xBF's photo
0xBF

Published on Apr 21, 2021

1 min read

Random

Pseudo Random Function

Use math/rand

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    num := rand.Int()
    fmt.Println("Random Integer:", num)

    // generate a number [0, 100)
    num = rand.Intn(100)
    fmt.Println("Random Integer:", num)

    // generate a float number
    fnum := rand.Float32()
    fmt.Println("Random Float:", fnum)

    // set seed then generate
    seed := rand.NewSource(time.Now().UnixNano())
    r1 := rand.New(seed)
    num = r1.Intn(100)
    fmt.Println("Random Integer:", num)
}

Crypto secure random

Use crypto/rand

package main

import (
    "crypto/rand"
    "encoding/hex"
    "fmt"
    "math/big"
)

func main() {
    // generate random integer <100
    num, _ := rand.Int(rand.Reader, big.NewInt(100))
    fmt.Println("Random Integer", num.Int64())

    // generate random string
    fmt.Println(genRandString(8))
    fmt.Println(genRandString(16))
}

func genRandString(size int) string {
    b := make([]byte, size)
    rand.Read(b)
    return hex.EncodeToString(b)
}

Generate UUID4

Use uuid package:

$ go get github.com/google/uuid
import (
    "encoding/hex"

    "github.com/google/uuid"
)

func genUUID4() string {
    uuid4, _ := uuid.NewRandom()
    bin, _ := uuid4.MarshalBinary()
    return hex.EncodeToString(bin)
}
 
Share this