How to convert a UUID string into UUID type

I have an array of string UUIDs that I want to change to UUID. Example of the data:

["69359037-9599-48e7-b8f2-48393c019135" "1d8a7307-b5f8-4686-b9dc-b752430abbd8"]

How can I change or parse it? I tried using uuid.fromString() method:

if len(a) == 2 {
    user1 := a[0]
    a[0], _ = uuid.FromString(a[0])
}

However, this gives me an error

FromString returns UUID parsed from string input. Input is expected in a form accepted by UnmarshalText.

Upvotes: 13

Views: 66645

Answers (2)

dahias42
dahias42

Reputation: 59

With github.com/google/uuid use the function

func Parse(s string) (UUID, error)

You also can use func MustParse(s string) UUI which auto-panics in case of an error.

See the docs for details: uuid package

Upvotes: 5

blackgreen
blackgreen

Reputation: 44665

With github.com/gofrs/uuid/v5, use uuid.FromString.

FromString returns UUID parsed from string input. Input is expected in a form accepted by UnmarshalText.

This method returns UUID or an error in case the parsing failed. You have two options to avoid explicit error handling:

  • FromStringOrNil, which returns only a UUID, but possibly nil in case of error
  • Must, which panics when the error of FromString is not nil. You use like:
uuid.Must(uuid.FromString("69359037-9599-48e7-b8f2-48393c019135"))

WARNING: satori/go.uuid, the older popular UUID package, nowadays is unmaintained and has unfixed issues. The package gofrs/uuid mentioned above is a maintained fork. From the package documentation:

We recommend using v2.0.0+ of this package, as versions prior to 2.0.0 were created before our fork of the original package and have some known deficiencies.


With github.com/google/uuid, use uuid.Parse. The rest of the pattern is the same as satori/uuid.


In your specific case, it looks like there's no problem in parsing the UUIDs, however the code you posted doesn't seem to produce the error you mention. Instead there is another problem:

a[0], _ = uuid.FromString(a[0])

you are attempting to reassign the value of uuid.FromString, which is a UUID to a[0] which is, presumably, a string.

The following code works fine (see it on Go Play):

var a = []string{"69359037-9599-48e7-b8f2-48393c019135", "1d8a7307-b5f8-4686-b9dc-b752430abbd8"}

func main() {

if len(a) == 2 {
        user1 := a[0]
        s, _ := uuid.FromString(a[0])

        fmt.Println(user1) // prints 69359037-9599-48e7-b8f2-48393c019135
        fmt.Println(s) // prints 69359037-9599-48e7-b8f2-48393c019135
    }
}

Upvotes: 21

Related Questions