如何削减golang中的uuid? [英] How to cut uuid in golang?

查看:194
本文介绍了如何削减golang中的uuid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了制作半随机slu,,我想使用uuid的前8个字符。所以我有

  import(
fmt
github.com/satori/go.uuid


u1:= uuid.NewV4()
fmt.Println(u1:,u1)

符文:= []符文( u1)
slug:= string(符文[0:7])

我得到这个错误:

lockquote

无法将u1(类型uuid.UUID)转换为类型[] rune


我该如何解决它?

我只是看了看源代码)UUID是 [16] byte 的别名,所以你不能将它用于符文数组,而不是你想要的。



试试这个:

  s:= hex.EncodeToString(u1 .Bytes()[:4])

这会给你8个十六进制数字。但是,这仍然是一个迂回的做事方式。一个v4的UUID是随机的,除了某些位,所以如果你没有使用整个UUID,那么直接产生4个随机字节就更简单了。使用 math / rand (必须接种)或加密中的 Read()函数/ rand (这是UUID库使用的)。

  b:= make([] byte,4)
rand.Read(b)// Does not实际上失败
s:= hex.EncodeToString(b)


In order to make semi-random slugs, I'd like to use first 8 characters of uuid. So I have

import (
    fmt
    "github.com/satori/go.uuid"
)

    u1 := uuid.NewV4()
    fmt.Println("u1 :", u1)

    runes := []rune(u1)
    slug := string(runes[0:7]) 

But in compile time I get this error:

cannot convert u1 (type uuid.UUID) to type []rune

How can I fix it?

解决方案

In that package (I just looked at the source code) a UUID is an alias for [16]byte, so you cannot concert it to a rune array, not that you want to.

Try this:

s := hex.EncodeToString(u1.Bytes()[:4])

This will give you 8 hex digits. However, this is still a roundabout way of doing things. A v4 UUID is random except for certain bits, so if you are not using the whole UUID it is more straightforward to just generate 4 random bytes. Use the Read() function in math/rand (which must be seeded) or crypto/rand (which is what the UUID library uses).

b := make([]byte, 4)
rand.Read(b) // Doesn’t actually fail
s := hex.EncodeToString(b)

这篇关于如何削减golang中的uuid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆