Home  >  Article  >  Backend Development  >  How to generate random string in Golang?

How to generate random string in Golang?

王林
王林Original
2024-06-05 17:23:411025browse

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.

如何在 Golang 中生成随机字符串?

How to generate random strings in Golang?

Generating random strings in Golang is very simple, just use the RandStringBytes function in the crypto/rand package.

Syntax

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.

Usage

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)
}

Practical case

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn