Jill Clover
Jill Clover

Reputation: 2328

How to get uuid in the form of "9e316d9e-a018fdc02a8352dea61ffd1d"?

I know how to get uuid in the form of uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, but I am required to get uuid in the form of "9e316d9e-a018fdc02a8352dea61ffd1d".

I am using https://github.com/satori/go.uuid.

I tried but I cannot come up with the item to search on Google. (If you know the search item, then it is obvious).

Upvotes: 0

Views: 489

Answers (2)

colm.anseo
colm.anseo

Reputation: 22037

You can do it in one line:

// var u uuid.UUID
fmt.Sprintf("%x-%x", u[:4], u[4:])

Playground example.


Edit:

Since fmt.Sprintf is not the most efficient method for encoding, you could model off of UUID.String() with this:

buf := make([]byte, 33)
hex.Encode(buf, u[:4])
buf[8] = '-'
hex.Encode(buf[9:], u[4:])
return string(buf)

Playground

Upvotes: 1

sedhossein
sedhossein

Reputation: 19

It is not possible since a UUID is a 16-byte number per definition. But of course, you can generate 8-character long unique strings with substring-ing and unix timestamp.

Also be careful with generating longer UUIDs and substring-ing them, since some parts of the ID may contain fixed bytes (e.g. this is the case with MAC, DCE and MD5 UUIDs) and this form of UUIDs 9e316d9e-a018fdc02a8352dea61ffd1d has no Guarantee to being really unique.

Upvotes: 0

Related Questions