How to convert String to Primitive.ObjectID in Golang?

Issue

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 ?

Solution

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

Answered By – icza

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.