如何在golang中切割uuid?

How to cut uuid in golang?

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

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

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

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

但是在编译时我得到这个错误:

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

我该如何解决?

无需将 UUID 转换为 []runeUUID type is stored in a binary representation as a [16]byte. There is a UUID.String() 方法可用于转换为字符串,然后对其进行切片。

 slug := u1.String()[:7]

在那个包中(我刚刚查看了源代码)UUID 是 [16]byte 的别名,所以你不能将它与符文数组协调,不是你想要的。

试试这个:

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

这将为您提供 8 个十六进制数字。但是,这仍然是一种迂回的做法。除了某些位之外,v4 UUID 是随机的,因此如果您不使用整个 UUID,则只生成 4 个随机字节会更直接。在 math/rand(必须播种)或 crypto/rand(这是 UUID 库使用的)中使用 Read() 函数。

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