英文:
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
types
的String()
方法可能会产生任意字符串表示。解析它可能并不总是可能的,因为它可能不包含原始值所持有的所有信息,或者它可能没有以可解析的方式“呈现”。还不能保证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>
这个解决方案可以改进,以在字符串表示中查找"
字符,并使用索引而不是固定的10
和34
,但是你不应该首先传输和解析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("ObjectID(%q)", id.Hex())
}
Which results in a string like this:
ObjectID("4af9f070cc10e263c8df915d")
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("4af9f070cc10e263c8df915d")
ObjectID("4af9f070cc10e263c8df915d") <nil>
This solution could be improved to find "
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()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论