如何在 golang 中生成一组确定的 UUID

How to generate a deterministic set of UUIDs in golang

我正在做一些测试,如果我们的代码使用一组已知的 UUID 会很有用。但是,我无法弄清楚如何在 golang 中创建一组确定的 UUID。

我尝试了几种方法,但似乎都不起作用:


type KnownReader struct {
    store *Store
}

type Store struct {
    val uint16
}

func (r KnownReader) Read(p []byte) (n int, err error) {
    ret := r.store.val
    r.store.val = ret + 1
    fmt.Printf("\nStore: %v", r.store.val)
    p = make([]byte, 4)
    binary.LittleEndian.PutUint16(p, uint16(ret))
    fmt.Printf("\nreader p: % x", p)
    return binary.MaxVarintLen16, nil
}

func main() {
    r := KnownReader{
        store: &Store{val: 111},
    }
    uuid.SetRand(r)
    u, _ := uuid.NewRandomFromReader(r)
    fmt.Printf("\n%v",u)
    u, _ = uuid.NewRandomFromReader(r)
    fmt.Printf("\n%v",u)
}

---- OUTPUT ----

Store: 1
reader p: 00 00 00 00
Store: 2
reader p: 01 00 00 00
Store: 3
reader p: 02 00 00 00
Store: 4
reader p: 03 00 00 00
Store: 5
reader p: 04 00 00 00
Store: 6
reader p: 05 00 00 00
00000000-0000-4000-8000-000000000000
Store: 7
reader p: 06 00 00 00
Store: 8
reader p: 07 00 00 00
Store: 9
reader p: 08 00 00 00
Store: 10
reader p: 09 00 00 00
Store: 11
reader p: 0a 00 00 00
Store: 12
reader p: 0b 00 00 00
00000000-0000-4000-8000-000000000000

如您所见,UUID 在调用之间不会更改

我也试过使用 uuid.FromBytes,但似乎也不起作用:


func getbytes(num uint16) []byte {
    p := make([]byte, 4)
    binary.LittleEndian.PutUint16(p, num)
    fmt.Printf("\ngetbytes p: % x", p)
    return p
}

func main() {
    var i uint16 = 0
    fmt.Printf("\nout getbytes: % x", getbytes(i))
    u, _ := uuid.FromBytes(getbytes(i))
    i = i + 1
    fmt.Printf("\nUUID: %v", u)
    fmt.Printf("\nout getbytes: % x", getbytes(i))
    u, _ = uuid.FromBytes(getbytes(i))
    fmt.Printf("\nUUID: %v", u)
}

---- OUTPUT ----

getbytes p: 00 00 00 00
out getbytes: 00 00 00 00
getbytes p: 00 00 00 00
UUID: 00000000-0000-0000-0000-000000000000
getbytes p: 01 00 00 00
out getbytes: 01 00 00 00
getbytes p: 01 00 00 00
UUID: 00000000-0000-0000-0000-000000000000

如您所见,这里的 UUID 仍然相同。

所以,有什么我想念的吗?如何获得一组一致的 UUID?

谢谢

谢谢 Adrian,我想我找到了答案:

rnd := rand.New(rand.NewSource(1))
uuid.SetRand(rnd)
u, _ = uuid.NewRandomFromReader(rnd)
fmt.Printf("\n%v", u)
u, _ = uuid.NewRandomFromReader(rnd)
fmt.Printf("\n%v", u)

--- OUTPUT ---

52fdfc07-2182-454f-963f-5f0f9a621d72
9566c74d-1003-4c4d-bbbb-0407d1e2c649