How to Generate UUID in Golang

UUID stands for Universally Unique Identifier. It is a 128-bit value used for a unique identification Foundation. UUIDs provide uniqueness as they generate ids based on time, cursor movement, and system hardware (MAC, etc.).

To generate UUID in Golang, you can use the exec.Command(‘uuidgen’)” or “uuid.New()” method from the UUID package.

Method 1: Using exec.Command() function

The exec.Command() function is used to “execute external commands”. The uuidgen command is a command-line utility that generates Universally Unique Identifiers (UUIDs).

Example

package main

import (
  "fmt"
  "os/exec"
)

func main() {
  // Create a new command.
  cmd := exec.Command("uuidgen")

  // Get the output of the command.
  output, err := cmd.Output()
  if err != nil {
    // Handle the error.
    panic(err)
  }

  // Print the output.
  fmt.Printf("%s", output)
}

Output

1A47EDC8-C3FD-47DC-805E-91CCA2644CD7

The “uuidgen” command is a helpful tool for generating UUIDs. UUIDs are used for various purposes, such as identifying objects in a database or tracking events.

Method 2: Using uuid.New() function

Follow the below steps to install the UUID package in Golang.

  1. Create a project folder and go inside that folder.
  2. Open the terminal and initialize a Golang project using this command: go mod init gfg.
  3. Install the UUID package using this command: go get github.com/google/uuid

That’s it. Now, the package is installed in your project folder. 

You can import the package using this code: import(github.com/google/uuid“).

How to Use UUID Package to Generate UUID

To generate a UUID using the github.com/google/uuid package in Go, you can use the uuid.New() function. The uuid.New() function generates a new UUID of version 4, a randomly generated UUID.

The New() function returns a uuid.UUID value which contains the generated UUID.

package main

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

func main() {
  uuid := uuid.New()
  fmt.Println("UUID:", uuid)
}

Output

UUID: d8b60078-5638-4840-8637-f9e3f638f5c5

In this code example, we imported the github.com/google/uuid package and called the uuid.New() function to generate a new UUID. The New() function returns a uuid.UUID value which contains the generated UUID.