How to Generate UUID in Golang

Use the uuid.New() method to generate a UUID in Golang. To use the UUID in Golang, import the third-party package “uuid”. This package is based on the github.com/google/uuid package.

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

How to Install UUID package in Golang

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. 

Now, 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 import the github.com/google/uuid package and call the uuid.New() function to generate a new UUID. The New() function returns a uuid.UUID value which contains the generated UUID.

Golang uuid.New().String()

Go uuid.New().String() function generates a new UUID of version 4 and returns it as a string.

The github.com/google/uuid package provides the uuid.New() function that returns a new UUID of version 4, randomly generated. The String() method returns the UUID as a string.

package main

import (
  "fmt"

  "github.com/google/uuid"
)

func main() {
  uuidString := uuid.New().String()
  fmt.Println("UUID_STRING:", uuidString)
}

Output

UUID_STRING: 40f65007-beb6-4457-a0c2-fa81f009bec6

In the code example, we called uuid.New() function to generate a new UUID, and then we call String() to return the UUID as a string. The uuidString variable will contain the UUID as a string.

Conclusion

You can generate UUIDs using the github.com/google/uuid package, which provides functions like uuid.New() and uuid.New().String() functions to generate version 1 and version 4 UUIDs. The generated UUIDs can be returned values or as strings.

Leave a Comment