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:
uuid
package using the following command:go get github.com/google/uuid
uuid
package in your Go code:import "github.com/google/uuid"
uid := uuid.New()
fmt.Println(uid.String()) // Print the generated UUID as a string
uid, err := uuid.Parse("da725c02-54bd-4a77-bdb6-6e8b8a2a43b4")
if err != nil {
fmt.Println("Failed to parse UUID:", err)
}
fmt.Println(uid)
uid1 := uuid.New()
uid2 := uuid.New()
if uid1 == uid2 {
fmt.Println("UUIDs are equal")
} else {
fmt.Println("UUIDs are not equal")
}
nsUUID := uuid.MustParse("892ab431-763a-4391-b0d2-9f0277f41878") // Namespace UUID
name := "example.com"
uid := uuid.NewSHA1(nsUUID, []byte(name))
fmt.Println(uid)
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.