0

I read here how to convert string efficiently in GO using either bytes.Buffer or strings.Builder. So how do I achieve the same in uuid im using satori/go.uuid, since doing this

var buffer bytes.Buffer
var s string
for i := 0; i < 2; i++ {
  s = buffer.WriteString(uuid.Must(uuid.NewV4()))
}

produce this error Cannot use 'uuid.Must(uuid.NewV4())' as type string.

My goal was so the 's' would be like this 15094a36-8827-453a-b27a-598421dbd73b-803bc133-dbc5-4629-9a2e-ef8ed3f1372e

machmum
  • 49
  • 1
  • 15
  • I'm using this https://github.com/satori/go.uuid, docs said uid is [16] byte type. how can I concatenate uuid then? – machmum Mar 31 '18 at 10:15

1 Answers1

3

The type of uuid.Must(uuid.NewV4()) is uuid.UUID, not string. Call the UUID.Sring() method to get a string. Call buffer.String() to get the string when done concatenating:

var buffer strings.Builder
for i := 0; i < 2; i++ {
    if i > 0 {
        buffer.WriteByte('-')
    }
    buffer.WriteString(uuid.Must(uuid.NewV4()).String())
}
s := buffer.String()

Another approach is to join the strings:

var uuids []string
for i := 0; i < 2; i++ {
    uuids = append(uuids, uuid.Must(uuid.NewV4()).String())
}
s := strings.Join(uuids, "-")
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • Add `buffer.WriteString("-")` to the concatenate, then remove the last char `"-"` from the concatenated string. Thanks Cerise! – machmum Mar 31 '18 at 10:53