简体   繁体   中英

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.

With github.com/satori/go.uuid , 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"))

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM