In order to make semi-random slugs, I'd like to use first 8 characters of uuid. So I have
import (
fmt
"github.com/satori/go.uuid"
)
u1 := uuid.NewV4()
fmt.Println("u1 :", u1)
runes := []rune(u1)
slug := string(runes[0:7])
But in compile time I get this error:
cannot convert u1 (type uuid.UUID) to type []rune
How can I fix it?
In that package (I just looked at the source code) a UUID is an alias for [16]byte
, so you cannot concert it to a rune array, not that you want to.
Try this:
s := hex.EncodeToString(u1.Bytes()[:4])
This will give you 8 hex digits. However, this is still a roundabout way of doing things. A v4 UUID is random except for certain bits, so if you are not using the whole UUID it is more straightforward to just generate 4 random bytes. Use the Read()
function in math/rand
(which must be seeded) or crypto/rand
(which is what the UUID library uses).
b := make([]byte, 4)
rand.Read(b) // Doesn’t actually fail
s := hex.EncodeToString(b)
There is no need to convert the UUID
to a []rune
. That UUID
type is stored in a binary representation as a [16]byte
. There is a UUID.String()
method which you can use to convert to a string, then slice it.
slug := u1.String()[:7]