Search code examples
gouuidstring-concatenation

Concatenate uuid in golang


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


Solution

  • 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, "-")