我需要用UUID1生成一个唯一的文件名。
我当前的python代码是:
uuid.uuid1().hex[:16] // i need 16 chars file name
什么可能是golang的等价物?
谢谢!
发布于 2015-08-28 17:42:24
Go的标准库中没有guid或uuid类型,但有一些其他方法可以做到这一点,比如使用第三方程序包,如https://godoc.org/code.google.com/p/go-uuid/uuid或https://github.com/nu7hatch/gouuid
import "github.com/nu7hatch/gouuid"
id, err := uuid.NewV4()
这个答案还有另一个选项,它使用Unix命令行utils;Is there a method to generate a UUID with go language,尽管它似乎执行得不是很好。
发布于 2018-01-07 06:19:39
我相信您的问题陈述中存在阻抗不匹配,并且您的Python代码不会像您预期的那样工作。
正如在“”上的一些答案可以推断出的,以及在https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_(date-time_and_MAC_address)中清楚地描述的那样,UUID很可能是唯一的,只有在全部获取时才是唯一的,而不是部分获取,并且根本不一定是随机的,特别是在版本1实际上是相当可预测的情况下,因为它基于生成它的主机的日期/时间和MAC地址。
因此,最好的方法可能是使用类似于其中一个answers to the prior mentioned question中的代码的东西,根据您自己的规范根据crypto/rand
实际生成一个随机文件名,并且不会误用这些库,这些库不一定会为手头的任务提供所需的随机性。
https://play.golang.org/p/k2V-Mc5Y31e
package main
import (
"crypto/rand"
"fmt"
)
func random_filename_16_char() (s string, err error) {
b := make([]byte, 8)
_, err = rand.Read(b)
if err != nil {
return
}
s = fmt.Sprintf("%x", b)
return
}
func main() {
s, _ := random_filename_16_char()
fmt.Println(s)
}
https://stackoverflow.com/questions/32276773
复制