我应该如何更改解析方法或更正随机方法

我想生成一个随机的 17 位数字字符串并通过 golang 将其解析为 uint64,这是我的代码:


const msgMaxValue      = 100000000000000000

s := fmt.Sprintf("%17v", rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(msgMaxValue))

log.Info("s:", s)

msgId, err := strconv.Atoi(s)

错误是:语法无效,我发现随机值中有一个空格但不知道为什么,我应该如何解决它,谢谢你


侃侃无极
浏览 80回答 1
1回答

慕无忌1623718

已通过“crypto/rand”修复它,下面是代码:func CreateRandomNumber(len int) (string, error) {&nbsp; &nbsp; var numbers = []byte{1, 2, 3, 4, 5, 7, 8, 9}&nbsp; &nbsp; var container string&nbsp; &nbsp; length := bytes.NewReader(numbers).Len()&nbsp; &nbsp; for i := 0; i < len; i++ {&nbsp; &nbsp; &nbsp; &nbsp; random, err := rand.Int(rand.Reader, big.NewInt(int64(length)))&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Error("random error:", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "", err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; container += fmt.Sprintf("%d", numbers[random.Int64()])&nbsp; &nbsp; }&nbsp; &nbsp; return container, nil}然后strconv.Atoi得到一个 int 类型号就可以了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go