How to generate a version 4 UUID with Go

How to generate a version 4 UUID with Go

There are several versions of UUIDs, and in this article we will focus on generating a version 4 UUID using the Go programming language.

A Universally Unique Identifier (UUID) is a unique identifier that is used universally in many contexts, such as identifiers for resources, database keys, and more. There are several versions of UUIDs, and in this article we will focus on generating a version 4 UUID using the Go programming language.

A version 4 UUID is a randomly generated identifier, based on the concept of randomness rather than information such as timestamps or MAC addresses (as with other versions of UUIDs). A v4 UUID has a fixed length of 128 bits, and the probability of two randomly generated UUIDs being the same is extremely low, making it ideal for unique identifiers.

To generate a version 4 UUID, we will use an external package called github.com/google/uuid. This package, developed by Google, provides a complete implementation of UUIDs for Go.


go get github.com/google/uuid

Now we are ready to write the code needed to generate a v4 UUID. Open the main.go file and insert the following code:


package main

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

func main() {
  // Generate a new version 4 UUID
  uuid := uuid.New()
  fmt.Println("Generated UUID v4:", uuid.String())
}

Conclusion

In this article, we have seen how to generate a version 4 UUID using Go. This process is quite simple thanks to the github.com/google/uuid package, which provides a robust and easy-to-use implementation for working with UUIDs in Go. This technique is especially useful when you need unique identifiers for resources or entities in your project.