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

编程入门 行业动态 更新时间:2024-10-08 08:33:04
本文介绍了如何使用Golang在长度范围内生成唯一的随机字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

如果通用唯一,请参阅: en.wikipedia/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: en.wikipedia/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在长度范围内生成唯一的随机字符串?

本文发布于:2023-10-26 06:46:51,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:范围内   字符串   如何使用   长度   Golang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!