Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you generate a random uint64 in Go?

Tags:

random

go

Go's math/random library is missing a function to generate 64-bit numbers. This has been an open issue for about four years. In the meantime, what does a workaround look like?

like image 702
Chris Martin Avatar asked Sep 28 '16 19:09

Chris Martin


1 Answers

Edit: Go 1.8 added a rand.Uint64() function and a Rand.Uint64() method, so you can directly use those.

The rest of the answer pre-dates Go 1.8.


The easiest would be to call rand.Uint32() twice:

func Uint64() uint64 {
    return uint64(rand.Uint32())<<32 + uint64(rand.Uint32())
}

Another option is to call rand.Read() (was added in Go 1.7) to read 8 bytes, then use the encoding/binary package to obtain a uint64 value from it:

func Uint64() uint64 {
    buf := make([]byte, 8)
    rand.Read(buf) // Always succeeds, no need to check error
    return binary.LittleEndian.Uint64(buf)
}

Note: as the doc of rand.Read() states, it always reads as many bytes as the length of the passed slice, and it always returns nil error, so no need to check error in this case.

Note #2: you could also use binary.BigEndian instead of binary.LittleEndian, as we're generating a random number using all its bytes, order of bytes is completely irrelevant.

like image 159
icza Avatar answered Sep 22 '22 17:09

icza