How to convert a Postgres UUID back to human-readable string in Go?

huangapple go评论95阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2022年2月16日 06:05:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/71133965.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定