gpt4 book ai didi

go - 如何以特定模式生成 UUID

转载 作者:IT王子 更新时间:2023-10-29 02:30:38 27 4
gpt4 key购买 nike

我正在尝试以特定模式在 Go 中生成 UUID。我正在处理的程序需要生成类似于现有 uuid 字符串的各种 uuid。因此该程序将读取现有的 uuid(其格式将来可能会更改)并生成一个相同格式的新 uuid 以替换现有的 uuid。

我使用了“github.com/satori/go.uuid”包来生成一个uuid。我正在使用的示例代码低于我在网上找到的代码。

由于该程序的多个实例将并行部署,因此我想避免生成的 uuid 发生冲突或重复。

    package main

import (
"fmt"
"github.com/satori/go.uuid"
)

func main() {
// Creating UUID Version 4
// panic on error
u1 := uuid.Must(uuid.NewV4(), nil)
fmt.Printf("UUIDv4: %s\n", u1)

// or error handling
u2:= uuid.NewV4()

fmt.Printf("UUIDv4: %s\n", u2)

/* Formats needed:
2286664c688130096c9ce9008e4d97fb
6abb173a-b134-49f2-aa88-9dff5dab12a1 (This is obtained from the above code)
C8-3C-9C-64-61-70-62-B9-34-AC-9A-20-C9-EF-1D-6D
*/
}

最佳答案

UUID 是 128 位;这是一个足够大的空间,碰撞几乎不可能发生。

来自 https://en.wikipedia.org/wiki/Universally_unique_identifier :

When generated according to the standard methods, UUIDs are for practical purposes unique, without depending for their uniqueness on a central registration authority or coordination between the parties generating them, unlike most other numbering schemes. While the probability that a UUID will be duplicated is not zero, it is close enough to zero to be negligible.

Thus, anyone can create a UUID and use it to identify something with near certainty that the identifier does not duplicate one that has already been, or will be, created to identify something else. Information labeled with UUIDs by independent parties can therefore be later combined into a single database or transmitted on the same channel, with a negligible probability of duplication.

UUID 的全部意义,也就是它们如此之大的原因,是为了避免没有同步的冲突。根据同一篇文章,为了达到 50% 的碰撞几率需要:

generating 1 billion UUIDs per second for about 85 years, and a file containing this many UUIDs, at 16 bytes per UUID, would be about 45 exabytes, many times larger than the largest databases currently in existence, which are on the order of hundreds of petabytes.

关于go - 如何以特定模式生成 UUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154909/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com