Go random string generation method/elegant method

Go random string generation method/elegant method

1:
func GetRandomStr1(n int) string {
	str := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	var result []byte
	bytesLen := len(bytes)
	
    for i := 0; i < n; i++ {
		result = append(result, bytes[rand.Intn(bytesLen)])
    }

    return string(result)
}

2:
func GetRandomStr2(n int) string {
    randBytes := make([]byte, n/2)
    rand.Read(randBytes)
	
    return fmt.Sprintf("%x", randBytes)
}

Comments

Popular posts from this blog

Python Receiving and parse JSON Data via UDP protocol

ubus lua client method and event registration code demo/example