From f910ac85cb024f6d523e2c9dab0518f227a0bfb9 Mon Sep 17 00:00:00 2001 From: Aneurin Barker Snook Date: Tue, 10 Oct 2023 22:06:23 +0100 Subject: [PATCH] add simple random package --- go.mod | 3 +++ random.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 go.mod create mode 100644 random.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3d4e852 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/recipeer/go/random + +go 1.21.2 diff --git a/random.go b/random.go new file mode 100644 index 0000000..6880f40 --- /dev/null +++ b/random.go @@ -0,0 +1,18 @@ +package random + +import "math/rand" + +// Str generates a random string of the specified length using an alphanumeric character set. +var Str = String([]rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")) + +// String returns a function that can be used to generate a random string of the specified length using the given character set. +func String(chars []rune) func(length int) string { + max := len(chars) + return func(length int) string { + s := make([]rune, length) + for i := range s { + s[i] = chars[rand.Intn(max)] + } + return string(s) + } +}