如何使用Golang在长度范围内生成唯一的随机字符串?

我想在长度范围内生成唯一的随机字符串。 例如,我将长度设置为10,并且每次生成的字符串都是唯一的。 </ p>
</ div>

展开原文

原文

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 .

dov11020
dov11020 你试过什么了?照原样,这个问题对于StackOverflow来说是开放的。
大约 4 年之前 回复

1个回答

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

downloadbooks_2014
downloadbooks_2014 也相关/有用:在Go中以短字符串形式输出UUID
大约 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问