How to generate and work with UUIDs (Universally Unique Identifiers) in Go?

In Go, you can generate and work with UUIDs (Universally Unique Identifiers) using the github.com/google/uuid package. Here's how you can use it:

  1. Install the uuid package using the following command:
go get github.com/google/uuid
  1. Import the uuid package in your Go code:
import "github.com/google/uuid"
  1. Generating a UUID:
uid := uuid.New() fmt.Println(uid.String()) // Print the generated UUID as a string
  1. Parsing a UUID from a string:
uid, err := uuid.Parse("da725c02-54bd-4a77-bdb6-6e8b8a2a43b4") if err != nil { fmt.Println("Failed to parse UUID:", err) } fmt.Println(uid)
  1. Comparing UUIDs for equality:
uid1 := uuid.New() uid2 := uuid.New() if uid1 == uid2 { fmt.Println("UUIDs are equal") } else { fmt.Println("UUIDs are not equal") }
  1. Generating a version 5 UUID (based on SHA-1 hash):
nsUUID := uuid.MustParse("892ab431-763a-4391-b0d2-9f0277f41878") // Namespace UUID name := "example.com" uid := uuid.NewSHA1(nsUUID, []byte(name)) fmt.Println(uid)
  1. Generating a version 3 UUID (based on MD5 hash):
nsUUID := uuid.MustParse("892ab431-763a-4391-b0d2-9f0277f41878") // Namespace UUID name := "example.com" uid := uuid.NewMD5(nsUUID, []byte(name)) fmt.Println(uid)

Keep in mind that the uuid package provides different versions (3, 4, and 5) of UUIDs. Version 4 UUIDs are randomly generated, while versions 3 and 5 are based on hash algorithms.

That's it! You now have the basic knowledge of generating and working with UUIDs in Go using the uuid package.