如何在Golang中将字符串转换为Primitive.ObjectID?

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

How to convert String to Primitive.ObjectID in Golang?

问题

有类似的问题。但大多数情况下,它们使用Hex()(例如这里)来进行原始对象到字符串的转换。我正在使用String()进行转换。如何将其转换回原始对象类型?

英文:

There are questions similar to this. But mostly they are using Hex()(like here) for primitive Object to String conversion. I'm using String() for conversion. How do I convert it back to primitive Object type ?

答案1

得分: 1

typesString()方法可能会产生任意字符串表示。解析它可能并不总是可能的,因为它可能不包含原始值所持有的所有信息,或者它可能没有以可解析的方式“呈现”。还不能保证String()的“输出”随时间不变。

ObjectID.String()的当前实现如下:

func (id ObjectID) String() string {
    return fmt.Sprintf("ObjectID(%q)", id.Hex())
}

这将产生以下字符串:

ObjectID("4af9f070cc10e263c8df915d")

这是可解析的,你只需要取十六进制数,并将其传递给primitive.ObjectIDFromHex()

例如:

id := primitive.NewObjectID()
s := id.String()
fmt.Println(s)

hex := s[10:34]
id2, err := primitive.ObjectIDFromHex(hex)
fmt.Println(id2, err)

这将输出(在Go Playground上尝试):

ObjectID("4af9f070cc10e263c8df915d")
ObjectID("4af9f070cc10e263c8df915d") <nil>

这个解决方案可以改进,以在字符串表示中查找"字符,并使用索引而不是固定的1034,但是你不应该首先传输和解析ObjectID.String()的结果。你应该首先使用它的ObjectID.Hex()方法,该方法可以直接传递给primitive.ObjectIDFromHex()

英文:

The String() method of types may result in an arbitrary string representation. Parsing it may not always be possible, as it may not contain all the information the original value holds, or it may not be "rendered" in a way that is parsable unambiguously. There's also no guarantee the "output" of String() doesn't change over time.

Current implementation of ObjectID.String() does this:

func (id ObjectID) String() string {
	return fmt.Sprintf(&quot;ObjectID(%q)&quot;, id.Hex())
}

Which results in a string like this:

ObjectID(&quot;4af9f070cc10e263c8df915d&quot;)

This is parsable, you just have to take the hex number, and pass it to primitive.ObjectIDFromHex():

For example:

id := primitive.NewObjectID()
s := id.String()
fmt.Println(s)

hex := s[10:34]
id2, err := primitive.ObjectIDFromHex(hex)
fmt.Println(id2, err)

This will output (try it on the Go Playground):

ObjectID(&quot;4af9f070cc10e263c8df915d&quot;)
ObjectID(&quot;4af9f070cc10e263c8df915d&quot;) &lt;nil&gt;

This solution could be improved to find &quot; characters in the string representation and use the indices instead of the fixed 10 and 34, but you shouldn't be transferring and parsing the result of ObjectID.String() in the first place. You should use its ObjectID.Hex() method in the first place, which can be passed as-is to primitive.ObjectIDFromHex().

huangapple
  • 本文由 发表于 2022年1月28日 15:16:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/70890072.html
匿名

发表评论

匿名网友

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

确定