In Golang, random strings can be generated by using the RandStringBytes function in the crypto/rand package. This function accepts two parameters, the first parameter specifies the length of the random string to be generated, and the second parameter is a byte array specifying the range of characters to use.
Generating random strings in Golang is very simple, just use the RandStringBytes
function in the crypto/rand
package.
func RandStringBytes(n int, alphabet []byte) ([]byte, error)
Where:
n
Specifies the length of the random string to be generated. alphabet
is a byte array specifying the range of characters to use. The following is an example of using the RandStringBytes
function to generate a random string:
package main import ( "crypto/rand" "fmt" ) func main() { n := 10 charset := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") b, err := rand.RandStringBytes(n, charset) if err != nil { fmt.Println(err) return } fmt.Printf("随机字符串:%s\n", b) }
Generate a random alphanumeric string of the specified length:
package main import ( "crypto/rand" "fmt" ) func main() { n := 10 charset := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") b, err := rand.RandStringBytes(n, charset) if err != nil { fmt.Println(err) return } fmt.Printf("随机字符串:%s\n", b) }
Generate a random lowercase alphanumeric string of the specified length:
package main import ( "crypto/rand" "fmt" ) func main() { n := 10 charset := []byte("abcdefghijklmnopqrstuvwxyz") b, err := rand.RandStringBytes(n, charset) if err != nil { fmt.Println(err) return } fmt.Printf("随机字符串:%s\n", b) }
Generate the specified Random hexadecimal string of length:
package main import ( "crypto/rand" "fmt" ) func main() { n := 10 charset := []byte("0123456789abcdef") b, err := rand.RandStringBytes(n, charset) if err != nil { fmt.Println(err) return } fmt.Printf("随机字符串:%s\n", b) }
The above is the detailed content of How to generate random string in Golang?. For more information, please follow other related articles on the PHP Chinese website!