Go random uint8 and uint16

September 22, 2022

The standard math/rand package1 does not contain functions to generate random uint8 or uint16 numbers. 

// Don't forget to rand.Seed(...)
func RandUint16() uint16 {
	return uint16(rand.Intn(math.MaxUint16 + 1))
}
func RandUint8() uint8 {
	return uint8(rand.Intn(math.MaxUint8 + 1))
}

Why the +1?

Because the rand.Intn(int)2 function states that the upper bound is not inclusive. Thus meaning we will never be able to reach the highest possible number that an uint8 or uint16 can hold, unless we increment the the math.MaxUintX value by one.

// Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n).
// It panics if n <= 0.

Read also

Golang string to int
How to Create Linked Lists in Go
Embedding Files into Your Go Program
Implementing a TCP Client and Server in Go: A Ping Pong Example
Discovering Go: A Deep Dive into Google's Own Programming Language
Implementing rate limiters in the Echo framework
Comments
References
1
2
go/rand.go at d7df872267f9071e678732f9469824d629cac595 · golang/go · GitHub

https://github.com/golang/go/blob/d7df872267f9071e678732f9469824d629cac595/src/math/rand/rand.go#L169

cached copy
Tags