Generating UUIDs in Go

UUIDs (Universally Unique Identifiers) serve as a standard for generating identifiers that are unique across time and space. In this blog post, we’ll explore how to generate UUIDs in Go using the google/uuid package. These can be especially useful when generating IDs across different systems - where it wouldn’t be possible to track using an auto incrementing integer.

Background

A UUID is a 128-bit number used to uniquely identify information in computer systems. The github.com/google/uuid package conforms to the RFC 4122 standard, which defines five versions of UUIDs, each for specific use cases. The most commonly used UUID versions are:

  • Version 1: Based on timestamp and MAC address.
  • Version 4: Generated using random numbers.

The google/uuid library primarily generates version 4 UUIDs, which offer a high level of randomness and are widely used in various applications.

Setup

We’ll be using the google/uuid package for this, so we’ll want to grab the latest copy, using this command:

1
go get -u github.com/google/uuid

Paste this into your terminal to install the package.

Using UUIDs in Code

Once we have everything installed, we can use the uuid package in our code. We’ve used New() to create our new string, which we can then output using Printf. Here’s an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import (
	"fmt"
	"github.com/google/uuid"
)

func main() {
	// Generate a UUID using the uuid.New() function.
	newUUID := uuid.New()
	fmt.Printf("Generated UUID: %s\n", newUUID)
}

Example In Action

min max in golang