如何使用Golang在长度范围内生成唯一的随机字符串? [英] How to generate unique random string in a length range using Golang?

查看:4748
本文介绍了如何使用Golang在长度范围内生成唯一的随机字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在长度范围内生成唯一的随机字符串。例如,我设置的长度是10.每次生成的字符串都是唯一的。


如果通用唯一,请参阅: https://en.wikipedia.org/wiki/Universally_unique_identifier

Out总共128位,类型4的UUID有6个保留位(版本4和其他2个保留位),所以随机生成的UUID有122个随机位。


为UUID请参阅:有没有一种方法可以生成带语言的UUID



如何显示它?二进制到文本编码

A UUID只是一个128位值。如果以十六进制格式显示它,它将是 32个字符长度

如果您想在10位,128/10 = 12.8 => 13位,那么您需要8192字母!

Golang中的字符串以UTF-8编码,因此您可以使用Unicode字母表:
Unicode具有足够的代码点,请参阅:可以用Unicode来映射多少个字符?



结论

如果您需要通用唯一性,请使用UUID。


并参阅:



或者如果您需要伪随机字符串长度为10,你可以使用这个(但不是通用唯一的):

pre $ $ $ $ $ $ $ $ $ $ $ $ $ $' crypto / rand
importfmt

func main(){
n:= 5
b:= make([] byte,n)
if _,err:= rand.Read(b); err!= nil {
panic(err)
}
s:= fmt.Sprintf(%X,b)
fmt.Println(s)
}

样本输出:

  FA8EA2FBCE 

另请参阅:在Go中输出UUID作为短字符串



和:是否有一种方法来生成一个UUID与去语言


I want to generate unique random string in a length range. For example, I set length is 10. and every time the generated string is unique .

解决方案

How unique is unique?
if Universally unique, see: https://en.wikipedia.org/wiki/Universally_unique_identifier
Out of a total of 128 bits, Type 4 UUIDs have 6 reserved bits (4 for the version and 2 other reserved bits), so randomly generated UUIDs have 122 random bits.

for UUID see: Is there a method to generate a UUID with go language

How to display it? ( Binary-to-text encoding )
A UUID is simply a 128-bit value. if you display it in Hex format it will be 32 character in length.
if you want in 10 place, 128/10=12.8 => 13 bit per place so you need 8192 alphabet !

string in Golang encoded in UTF-8 so you may use Unicode alphabet: Unicode has enough code points, see: How many characters can be mapped with Unicode?

conclusion:
if you need Universally unique just use UUIDs.

and see: How to generate a random string of a fixed length in golang?

or if you need pseudo random string with length 10, you may use this (but not Universally unique):

package main

import "crypto/rand"
import "fmt"

func main() {
    n := 5
    b := make([]byte, n)
    if _, err := rand.Read(b); err != nil {
        panic(err)
    }
    s := fmt.Sprintf("%X", b)
    fmt.Println(s)
}

sample output:

FA8EA2FBCE

also see: Output UUID in Go as a short string

and: Is there a method to generate a UUID with go language

这篇关于如何使用Golang在长度范围内生成唯一的随机字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆