Przeglądaj źródła

add simple random package

Aneurin Barker Snook 1 rok temu
commit
f910ac85cb
2 zmienionych plików z 21 dodań i 0 usunięć
  1. 3 0
      go.mod
  2. 18 0
      random.go

+ 3 - 0
go.mod

@@ -0,0 +1,3 @@
+module github.com/recipeer/go/random
+
+go 1.21.2

+ 18 - 0
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)
+	}
+}