4

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 .

Leviathan
  • 297
  • 1
  • 5
  • 10

1 Answers1

16

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

Community
  • 1
  • 1
  • Also related / useful: [Output UUID in Go as a short string](http://stackoverflow.com/questions/37934162/output-uuid-in-go-as-a-short-string) – icza Jul 17 '16 at 07:44