在 golang 中可以通过使用 crypto/rand 包中的 randstringbytes 函数生成随机字符串。该函数接受两个参数,第一个参数指定要生成的随机字符串的长度,第二个参
在 golang 中可以通过使用 crypto/rand 包中的 randstringbytes 函数生成随机字符串。该函数接受两个参数,第一个参数指定要生成的随机字符串的长度,第二个参数是一个字节数组,指定要使用的字符范围。
在 Golang 中生成随机字符串非常简单,只需使用 crypto/rand 包中的 RandStringBytes 函数即可。
func RandStringBytes(n int, alphabet []byte) ([]byte, error)
其中:
以下是使用 RandStringBytes 函数生成随机字符串的示例:
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)
}
生成指定长度的随机字母数字字符串:
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)
}
生成指定长度的随机小写字母字符串:
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)
}
生成指定长度的随机十六进制字符串:
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)
}
以上就是如何在 Golang 中生成随机字符串?的详细内容,更多请关注编程网其它相关文章!
--结束END--
本文标题: 如何在 Golang 中生成随机字符串?
本文链接: https://www.lsjlt.com/news/616284.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0