Search code examples
goreflectiontype-conversionuuid

Go: convert reflect.Value of type uuid.UUID (satori) back to uuid.UUID again


I'm trying to convert a reflected UUID back to an actual UUID object again but can't find a way, when I print the reflected value it looks correct, but when trying to convert I can't find a way.

package main

import (
  "fmt"
  "reflect"

  uuid "github.com/satori/go.uuid"
)

func main() {
  value := uuid.Must(uuid.NewV4())
  reflectedValue := reflect.ValueOf(value)
  fmt.Println(reflectedValue)
  result := reflectedValue.String()
  fmt.Println(result)
}

output:

$ go run main.go
0cca93f8-1763-4816-a2a0-09e7aeeb674c
<uuid.UUID Value>

How to convert reflectedValue to uuid.UUID directly or []byte/string so I can make a uuid.UUID object from that. Since fmt.Println manages to print the correct value it has to be possible to make the conversion, but I can't figure out how.

It seem like the uuid.UUID object has a data structure of 16 uint8 values.


Solution

  • Use a type assertion on the underlying value:

    u, ok := reflectedValue.Interface().(uuid.UUID)