A UUID contains 32 hexadecimal values grouped in 5 blocks. Where each block is separated by a hyphen.
This short guide will discover how to generate a UUID or GUID in the Go programming language.
Go UUID Package
Go does not have the support for generating UUID or GUID values in its standard library. However, there are third-party packages that allow us to perform these operations.
We will use the google/uuid package for Go in this article.
https://github.com/google/uuid
Install Go UUID Package
Before we use the package, we need to install it. We can do this by entering the command below:
Once installed, we can use the package to generate UUID values.
Generate UUID
To generate a UUID value, start by initializing a new project as:
go get github.com/google/uuid
Once executed successfully, create a uuid.go file and enter the code below:
import (
"fmt"
"github.com/google/uuid"
)
funcmain() {
uuid := uuid.New()
fmt.Println(uuid)
}
The code above should generate a new UUID value as shown:
You can also use the NewUUID() method to generate a new UUID value. An example code is as shown:
import (
"fmt"
"log"
"github.com/google/uuid"
)
funcmain() {
uuid, err := uuid.NewUUID()
if err != nil {
log.Fatal(err)
}
fmt.Println(uuid)
}
Similar to the New() method, it returns a new unique UUID value.
Conclusion
This article shows you how to use the google/uuid package to generate UUID values using the Go programming language.