Generate UUID in Golang


Universally Unique Identifier (UUID) is a 128-bit value that is used to uniquely identify objects or entities. UUID is widely used in computer systems for generating unique IDs for objects, documents, and data records. In Golang, we can generate UUID using the "github.com/google/uuid" package.

Installing the "github.com/google/uuid" Package

Before we can generate UUID in Golang, we need to install the "github.com/google/uuid" package. To install this package, run the following command in the terminal −

go get github.com/google/uuid

Generating UUID in Golang

Once we have installed the "github.com/google/uuid" package, we can use the "uuid" package to generate UUIDs. Here's an example code that demonstrates how to generate UUID in Golang −

Example

package main

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

func main() {
   // Generate a new UUID
   u := uuid.New()

   // Print the UUID
   fmt.Println(u.String())
}

In the above code, we first import the "fmt" package and the "github.com/google/uuid" package. We then use the "uuid.New()" function to generate a new UUID and store it in the variable "u". Finally, we print the UUID using the "u.String()" function.

Generating Version 4 UUID in Golang

The "github.com/google/uuid" package also provides a way to generate Version 4 UUIDs. Version 4 UUIDs are generated using random numbers, and they are generally considered more secure than other versions of UUIDs.

Here's an example code that demonstrates how to generate Version 4 UUID in Golang −

Example

package main

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

func main() {
   // Generate a new Version 4 UUID
   u := uuid.NewRandom()

   // Print the UUID
   fmt.Println(u.String())
}

In the above code, we use the "uuid.NewRandom()" function to generate a new Version 4 UUID and store it in the variable "u". Finally, we print the UUID using the "u.String()" function.

Conclusion

Generating UUID is a common task in computer systems, and Golang provides an easy way to generate UUID using the "github.com/google/uuid" package. In this article, we saw how to install the "github.com/google/uuid" package and how to use it to generate UUIDs in Golang. We also saw how to generate Version 4 UUIDs using the "uuid.NewRandom()" function.

Updated on: 18-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements