douqian1296 2017-12-06 13:57
浏览 430
已采纳

如何在golang中切掉uuid?

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?

  • 写回答

2条回答 默认 最新

  • douren1891 2017-12-06 14:09
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 YOLOv5在进行trainpy训练后为什么会出现这种情况(语言-python)
  • ¥15 关于远程桌面的鼠标位置转换
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据
  • ¥15 为什么openeluer里面按不了python3呢?
  • ¥15 关于#matlab#的问题:训练序列与输入层维度不一样