Generate a UUID in Go
Go is a compiled, statically typed programming language.
First designed in 2007 at Google, its goals were to create a modern programming language that improved upon the weaknesses in the other languages in use at Google. Although supported by Google, Go is open source and runs on Windows, Mac, Linux and FreeBSD.
How to Generate a UUID in Go
Although the Go programming language itself does not have built-in support for generating a UUID or GUID, there are quality 3rd party, open-source packages that you can use instead.
The Go package we recommend for generating UUIDs is called, go.uuid. It can generate Version 1, 2, 3, 4 and 5 UUIDs.
Installing the go.uuid
Package
To get started with the package, you'll need to install it. You can do this with the go
command:
% go get github.com/satori/go.uuid
Generating UUIDs
With the go.uuid
package installed, you can now use it in your Go code.
package mainimport ("fmt""github.com/satori/go.uuid")func main() {myuuid, err := uuid.NewV4()fmt.Println("Your UUID is: %s", myuuid)}
Explanation
- Line #5 imports the
go.uuid
package, providing access to theuuid
object. - Line #9 generates the Version 4 UUID and saves it in the variable,
myuuid
. - The output from line #10 will be something like:
Your UUID is: 83064af3-bb81-4514-a6d4-afba340825cd
The go.uuid
package has a number of other functions, such as for converting from a string representation
of
a UUID into a byte slice and back. You can read more about the
Go UUID package on its GoDoc project page.
How can we improve this page? Let us know!