How to generate unique random string in a length range using Golang?

馋奶兔 提交于 2020-01-21 12:51:55

问题


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 .


回答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



来源:https://stackoverflow.com/questions/38418171/how-to-generate-unique-random-string-in-a-length-range-using-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!