Open In App

Generate UUID in Golang

Last Updated : 15 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

UUID stands for Universally Unique Identifier. It is a 128-bit value used for a unique identification Foundation (OSF).
UUIDs provide uniqueness as it generates ids on the basis of time, cursor movement, system hardware (MAC, etc.), etc.
As a result, it is very likely that UUIDs are unique across space and time and are very difficult to guess as it is based on numerous factors. The UUID package in this article generates and inspects UUIDs based on RFC 4122 and DCE 1.1: Authentication and Security Services.

Advantages of UUID:

  • It can be used as a general utility to generate a unique random id.
  • It can also be used in cryptography and hashing applications.
  • It is useful in generating random documents, addresses, etc.

Generate UUID in Golang

Before generating UUID first of all we initialize a go project. So, create an empty directory for the new project. Initialize using the init command: go mod init projectName. This generates a go.mod file.

Example:

go mod init gfg

Create a new file main.go.

Output:

Create-a-new-file-main.go

Resulting directory structure:

 Directory-structure

The go code can be added int this main.go file and run using the following command:

go run main.go

There are two ways to generate a UUID:

  1. Using inbuilt library – os/exec
  2. Using uuid package by google – github.com/google/uuid

Now we will learn how to generate UUID in Golang using the following methods:

Generate UUID using os/exec

To generate UUID using os/exec follow the following steps:

Step 1: Import os/exec package for the UUID utility.

Step 2: Execute uuidgen command via imported os/exec package.

Step 3: Check for any error while generation.

Step 4: Print the generated UUID.

Filename: main.go

Go




package main
  
import (
    "fmt"
    "log"
    "os/exec"
)
  
func main() {
    newUUID, err := exec.Command("uuidgen").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Generated UUID:")
    fmt.Printf("%s", newUUID)
}


Output:

Output

Generate UUID google/uuid package

To generate UUID using google/uuid package follow the following steps:

Step 1: Install the google/uuid package using following command:

go get github.com/google/uuid

Output

This also creates a go.sum file and updates go.mod file adding the package details.

Step 2: import github.com/google/uuid package for the uuid utility

Step 3: Use uuid.New function of the imported uuid package

Step 4: Print the generated UUID

Filename: main.go

Go




package main
  
import (
    "fmt"
    "github.com/google/uuid"
)
  
func main() {
    id := uuid.New()
    fmt.Println("Generated UUID:")
    fmt.Println(id.String())
}


Output:

Final-output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads