# Golang 优雅地生成随机字符串
随机字符串都不保证唯一性,服务启动时需要对全局随机种子进行初始化
```
func init() {
rand.Seed(time.Now().UnixNano())
}
```
## 方法一 (常见,但不`优雅`)
```
func GetRandomString(n int) string {
str := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
bytes := []byte(str)
var result []byte
for i := 0; i < n; i++ {
result = append(result, bytes[rand.Intn(len(bytes))])
}
return string(result)
}
```
Benchmark压力测试 `8018 ns/op`
![image-7iOYcGn.png](https://static.studygolang.com/200808/760f0b0704e2a005b7d2e4778ce4f846.png)
## 方法二(`Docker ContainerID` 生成方法)
```
func GetRandomString2(n int) string {
randBytes := make([]byte, n/2)
rand.Read(randBytes)
return fmt.Sprintf("%x", randBytes)
}
```
Benchmark压力测试 `10595 ns/op`
![image-2E7hUwM.png](https://static.studygolang.com/200808/cf1bd3be0a0bc905c99a7ea98045ce50.png)