golang

Golang UUID

Universally Unique Identifier, or UUID for short, is a universally unique identifier consisting of a 128-bit number. It is mainly used to identify information since there is a duplicate value is near zero.

A UUID contains 32 hexadecimal values grouped in 5 blocks. Where each block is separated by a hyphen.

This short guide will discover how to generate a UUID or GUID in the Go programming language.

Go UUID Package

Go does not have the support for generating UUID or GUID values in its standard library. However, there are third-party packages that allow us to perform these operations.

We will use the google/uuid package for Go in this article.

https://github.com/google/uuid

Install Go UUID Package

Before we use the package, we need to install it. We can do this by entering the command below:

go get github.com/google/uuid

Once installed, we can use the package to generate UUID values.

Generate UUID

To generate a UUID value, start by initializing a new project as:

go mod init uuid

go get github.com/google/uuid

Once executed successfully, create a uuid.go file and enter the code below:

package main
import (
    "fmt"

    "github.com/google/uuid"
)
funcmain() {
    uuid := uuid.New()
    fmt.Println(uuid)
}

The code above should generate a new UUID value as shown:

2666ba9e-1290-4cf8-a72e-7455721beb2e

You can also use the NewUUID() method to generate a new UUID value. An example code is as shown:

package main
import (
    "fmt"
    "log"

    "github.com/google/uuid"
)
funcmain() {
    uuid, err := uuid.NewUUID()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(uuid)
}

Similar to the New() method, it returns a new unique UUID value.

cb41d235-7dc5-11ec-8559-98fc84d0af0e

Conclusion

This article shows you how to use the google/uuid package to generate UUID values using the Go programming language.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list