[转]GO UUID

Here is a simple UUID generator,it uses version 4,Pseudo Random,as described inRFC 4122

uuid.go


package uuid

import (
 "encoding/hex"
 "crypto/rand"
)

func GenUUID() (string,error) {
 uuid := make([]byte,16)
 n,err := rand.Read(uuid)
 if n != len(uuid) || err != nil {
 return "",err
 }
 // Todo: verify the two lines implement RFC 4122 correctly
 uuid[8] = 0x80 // variant bits see page 5
 uuid[4] = 0x40 // version 4 Pseudo Random,see page 7

 return hex.EncodetoString(uuid),nil
}
uuid_test.go



package uuid

import (
 "testing"
 )

func TestUUID(t *testing.T) {
    uuid,err := GenUUID()
    if  err != nil {
        t.Fatalf("GenUUID error %s",err)
    }
    t.Logf("uuid[%s]\n",uuid)
}

func BenchmarkUUID(b *testing.B) {
    m := make(map[string]int,1000) 
    for i := 0; i < b.N; i++ {
       uuid,err := GenUUID()
       if  err != nil {
        b.Fatalf("GenUUID error %s",err)
       } 
       b.StopTimer()
       c := m[uuid]
       if c > 0 {
         b.Fatalf("duplicate uuid[%s] count %d",uuid,c )
       } 
       m[uuid] = c+1
       b.StartTimer()
    }
}
command to build uuid.go
go build uuid.go

command to run test & benchmark:

go test -v -bench=".*UUID" uuid.go uuid_test.go

The source code of uuid.go and uuid_test.go are attached below.

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1&#160;Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...