Generating Unique Random Strings of Specific Length in Go
In Go, generating unique random strings within a specified length range presents a straightforward task. However, understanding the level of uniqueness desired is crucial.
Universally Unique UUIDs
If global uniqueness is a requirement, UUIDs (Universally Unique Identifiers) offer a robust solution. UUIDs comprise a 128-bit value, providing a vast pool of potential combinations. To generate a UUID in Go, consider the following approach:
<code class="go">import ( "fmt" "github.com/google/uuid" ) func main() { u := uuid.New() fmt.Println(u.String()) }</code>
Pseudo Random Strings
For a less universally unique option, Go's crypto/rand package provides a secure way to generate pseudo-random bytes. These bytes can be converted to a hexadecimal string, resulting in a pseudo-random string.
<code class="go">package main import ( "crypto/rand" "fmt" ) func main() { n := 10 b := make([]byte, n) if _, err := rand.Read(b); err != nil { panic(err) } s := fmt.Sprintf("%X", b) fmt.Println(s) }</code>
Other Considerations
The above is the detailed content of How to Generate Unique Random Strings of Specific Lengths in Go?. For more information, please follow other related articles on the PHP Chinese website!