Developer's Center
Golang

How to Generate a UUID in Go: A Comprehensive Guide

Are you looking for a way to generate Universally Unique Identifiers (UUIDs) in Go? Look no further! In this article, we will walk you through the process of generating UUIDs using the popular Go programming language. We will also provide detailed explanations for the code snippets, ensuring that you have a clear understanding of how it works.

Go, also known as Golang, is a powerful and efficient programming language developed by Google in 2007. It was designed to overcome the limitations of existing programming languages and provide a modern and streamlined approach to software development. Go is a compiled and statically typed language, making it ideal for building high-performance applications.

Generating UUIDs in Go

While Go does not have built-in support for generating UUIDs, there are excellent third-party packages available that can fulfill this requirement. One such package is go.uuid, a widely used open-source package that offers support for generating various versions of UUIDs.

Installing the go.uuid Package To get started, you will need to install the go.uuid package. Don't worry; it's a straightforward process. Simply execute the following command using the go command-line tool:

go get github.com/google/uuid

This command will download and install the go.uuid package, making it ready for use in your Go projects.

Generating UUIDs with go.uuid

Now that you have the go.uuid package installed, let's dive into the code and see how we can generate UUIDs in Go.

package main
 
import (
	"fmt"
	"github.com/google/uuid"
)
 
func main() {
  myuuid, err := uuid.NewV4()
  fmt.Println("The UUID is: %s", myuuid)
}

In this code snippet, we import the github.com/google/uuid package, which provides the necessary functions for generating UUIDs. The NewRandom() function is used to generate a random UUID, and any error encountered during the process is handled gracefully. Finally, we print the generated UUID to the console.

Understanding the Code

Let's break down the code and understand how it works:

  • Line #5 imports the github.com/google/uuid package, which grants us access to the uuid object and its functions.
  • Line #9 uses the NewRandom() function to generate a random UUID and assigns it to the myUUID variable.
  • Line #11 prints the generated UUID to the console, ensuring that it is displayed for further use.

Updated at 2023-11-21 Satori's uuid is unmaintained and contains a vulnerability (https://nvd.nist.gov/vuln/detail/CVE-2021-3538 (opens in a new tab)).