dptj13337 2013-02-28 07:58
浏览 532
已采纳

有没有一种用go语言生成UUID的方法

I have code that looks like this:

u := make([]byte, 16)
_, err := rand.Read(u)
if err != nil {
    return
}

u[8] = (u[8] | 0x80) & 0xBF // what does this do?
u[6] = (u[6] | 0x40) & 0x4F // what does this do?

return hex.EncodeToString(u)

It returns a string with a length of 32, but I don't think it is a valid UUID. If it is a real UUID, why is it a UUID, and what is the purpose of the code that modifies the value of u[8] and u[6].

Is there a better way of generating UUIDs?

  • 写回答

13条回答 默认 最新

  • dongsigan2636 2013-02-28 08:36
    关注
    u[8] = (u[8] | 0x80) & 0xBF // what's the purpose ?
    u[6] = (u[6] | 0x40) & 0x4F // what's the purpose ?
    

    These lines clamp the values of byte 6 and 8 to a specific range. rand.Read returns random bytes in the range 0-255, which are not all valid values for a UUID. As far as I can tell, this should be done for all the values in the slice though.

    If you are on linux, you can alternatively call /usr/bin/uuidgen.

    package main
    
    import (
        "fmt"
        "log"
        "os/exec"
    )
    
    func main() {
        out, err := exec.Command("uuidgen").Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s", out)
    }
    

    Which yields:

    $ go run uuid.go 
    dc9076e9-2fda-4019-bd2c-900a8284b9c4
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog