How to generate a random string of fixed length in Go?
Hello everyone! I just started learning Go and encountered a typical task: I need to generate random strings of a given length, for example, to create unique identifiers, tokens, or passwords. I wrote this code:
```go
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(RandString(10))
}
func RandString(n int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
```
The code seems to work, but I noticed strange behavior: every time I run the program, the same string is generated. I googled it and found out that I need to use `rand.Seed()`, but even after adding `rand.Seed`
No answers yet.
Log in to leave an answer
Blogs