英文:
How to convert a Postgres UUID back to human-readable string in Go?
问题
Go Postgres库定义了一个类型UUID
,如下所示:
type UUID struct {
UUID uuid.UUID
Status pgtype.Status
}
func (dst *UUID) Set(src interface{}) error {
// 省略部分代码
}
我的代码使用了这个库:
import pgtype/uuid
string_uuid := uuid.New().String()
fmt.Println("string_uuid =", string_uuid)
myUUID := pgtype.UUID{}
err = myUUID.Set(string_uuid)
if err != nil {
panic()
}
fmt.Println("myUUID.Bytes =", myUUID.Bytes)
fmt.Println("string(myUUID.Bytes[:]) =", string(myUUID.Bytes[:]))
以下是输出结果:
string_uuid = abadf98f-4206-4fb0-ab91-e77f4380e4e0
myUUID.Bytes = [171 173 249 143 66 6 79 176 171 145 231 127 67 128 228 224]
string(myUUID.Bytes[:]) = ����BO����C���
一旦将类型为pgtype.UUID{}
的myUUID
设置为这个值,我该如何将其恢复为原始的可读的UUID字符串abadf98f-4206-4fb0-ab91-e77f4380e4e0
?
英文:
The Go Postgres library defines a type UUID
as such:
type UUID struct {
UUID uuid.UUID
Status pgtype.Status
}
func (dst *UUID) Set(src interface{}) error {
<Remainder Omitted>
My code uses this library:
import pgtype/uuid
string_uuid := uuid.New().String()
fmt.Println("string_uuid = ", string_uuid)
myUUID := pgtype.UUID{}
err = myUUID.Set(string_uuid)
if err != nil {
panic()
}
fmt.Println("myUUID.Bytes = ", myUUID.Bytes)
fmt.Println("string(myUUID.Bytes[:]) = ", string(myUUID.Bytes[:]))
Here is the output:
string_uuid = abadf98f-4206-4fb0-ab91-e77f4380e4e0
myUUID.Bytes = [171 173 249 143 66 6 79 176 171 145 231 127 67 128 228 224]
string(myUUID.Bytes[:]) = ����BO����C���
How can I get back to the original human-readable UUID string abadf98f-4206-4fb0-ab91-e77f4380e4e0
once it is put into myUUID
which is of type pgtype.UUID{}
?
答案1
得分: 4
问题中的代码使用的是pgtype.UUID,而不是问题中提到的gofrs UUID。
pgtype.UUID类型没有获取UUID字符串表示的方法,但在应用程序代码中很容易实现:
s := fmt.Sprintf("%x-%x-%x-%x-%x", myUUID.Bytes[0:4], myUUID.Bytes[4:6], myUUID.Bytes[6:8], myUUID.Bytes[8:10], myUUID.Bytes[10:16])
如果要获取没有破折号的十六进制表示:
s := fmt.Sprintf("%x", myUUID.Bytes)
如果应用程序使用的是gofrs UUID,则使用:
s := myUUID.UUID.String()
英文:
The code in the question uses the pgtype.UUID, not the gofrs UUID linked from question's prose.
The pgtype.UUID type does not have a method to get the UUID string representation, but it's easy enough to do that in application code:
s := fmt.Sprintf("%x-%x-%x-%x-%x", myUUID.Bytes[0:4], myUUID.Bytes[4:6], myUUID.Bytes[6:8], myUUID.Bytes[8:10], myUUID.Bytes[10:16])
Do this if you want hex without the dashes:
s := fmt.Sprintf("%x", myUUID.Bytes)
If the application uses the gofrs UUID, then use:
s := myUUID.UUID.String()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论