How to generate a UUID in Go

Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It is often referred to as Golang because of its former domain name, golang.org, but its proper name is Go. Go is syntactically similar to C but has several features that make it more modern and easier to use. Some of these features include memory safety, garbage collection, structural typing, and CSP-style concurrency. Go was designed to improve programming productivity in an era of multicore, networked machines and large codebases. It aims to be efficient, readable, and usable.

This is how you generate a UUID in Go:

  1. package main
  2. import (
  3.     "fmt"
  4.     "github.com/google/uuid"
  5. )
  6. func main() {
  7.     id := uuid.New()
  8.     fmt.Println(id.String())
  9. }

This program uses the google/uuid package to generate a version 4 UUID. You can install this package by running go get github.com/google/uuid

Explanation

How to convert from a string to UUID in Go

This program uses the Parse function from the google/uuid package to convert a string representation of a UUID into a UUID value. The Parse function returns an error if the input string is not a valid UUID.

  1. package main
  2. import (
  3.     "fmt"
  4.     "github.com/google/uuid"
  5. )
  6. func main() {
  7.     uuidStr := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  8.     id, err := uuid.Parse(uuidStr)
  9.     if err != nil {
  10.         fmt.Println(err)
  11.         return
  12.     }
  13.     fmt.Println(id)
  14. }

Explanation