有没有一种方法可以用go语言生成UUID [英] Is there a method to generate a UUID with go language

查看:152
本文介绍了有没有一种方法可以用go语言生成UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

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

u [8] =(u [8] | 0x80 )& 0xBF //这是做什么的?
u [6] =(u [6] | 0x40)& 0x4F //这是什么?

return hex.EncodeToString(u)

它返回一个字符串长度为32,但我不认为这是一个有效的UUID。如果它是一个真正的UUID,为什么它是一个UUID,以及修改 u [8] 值的代码的目的是什么?有没有更好的方法来生成UUID?

>解决方案

  u [8] =(u [8] | 0x80)& 0xBF //目的是什么? 
u [6] =(u [6] | 0x40)& 0x4F //目的是什么?

这些行将字节6和8的值限制在特定范围内。 rand.Read 返回 0-255 范围内的随机字节,这些字符并非UUID的全部有效值。据我所知,这应该是为所有的切片值。



如果你在linux上,你可以调用 / 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 ,出)
}

其中:

  $ go run uuid.go 
dc9076e9-2fda-4019-bd2c-900a8284b9c4


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?

解决方案

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

这篇关于有没有一种方法可以用go语言生成UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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