douqian1296 2017-12-06 13:57
浏览 430


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

import (

    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)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥15 中级微观经济学,生产可能性边界问题
  • ¥15 TCP传输时不同网卡传输用时差异过大
  • ¥15 请各位看看我写的属于什么算法,或者有更正确的写法?
  • ¥15 html5 qrcode 扫描器
  • ¥15 爬取网页信息并保存需要完整代码