Generate UUID in GoLang

Table of Contents

1. Introduction to UUID

UUIDs are generated based on certain algorithms that ensure their uniqueness. A UUID consists of 32 hexadecimal digits, divided into five groups, separated by hyphens. The format of a UUID looks like this: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.

2. Using the uuid package

The simplest way to generate UUIDs in Golang is by using the uuid package from the popular package management system, Go Modules. This package provides a function New() that creates a new UUID.

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

func main() {
    id := uuid.New()
    fmt.Println(id)
}

3. Using the Google UUID library

Another way to generate UUIDs in Golang is by using the Google UUID library. This library provides a function NewUUID() that creates a new UUID.

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

func main() {
    id := uuid.NewUUID()
    fmt.Println(id)
}

4. Generating a UUID from a string

Sometimes, we may need to generate a UUID based on a specific string value. Golang provides a way to do this using the uuid.FromString() function.

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

func main() {
    str := "example-string"
    id := uuid.NewMD5(uuid.NamespaceURL, []byte(str))
    fmt.Println(id)
}

5. Conclusion

Generating UUIDs is an important task in software development, and Golang provides several options for generating them. In this tutorial, we explored different ways of generating UUIDs in Golang, including using the uuid package and the Google UUID library. We also learned how to generate a UUID from a string value.

By using these methods, you can easily generate unique identifiers for a wide range of applications in your Golang projects.

References

  1. Go Modules: https://pkg.go.dev/cmd/go
  2. uuid package: https://github.com/google/uuid
  3. Google UUID library: https://github.com/pborman/uuid