Welcome To Golang By Example

Generate a UUID/GUID in Go (Golang)

UUID also known as GUID is a 16 byte or 128-bit number. It is meant to uniquely identify something. Some of the properties of UUID are

705e4dcb-3ecd-24f3-3a35-3e926e4bded5

There are different libraries available for generating the UUID. Let’s see two libraries which can be used to generate UUID

https://github.com/google/uuid

Code:

package main

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

func main() {
    uuidWithHyphen := uuid.New()
    fmt.Println(uuidWithHyphen)
    uuid := strings.Replace(uuidWithHyphen.String(), "-", "", -1)
    fmt.Println(uuid)
}

Output:

cda6498a-235d-4f7e-ae19-661d41bc154c
cda6498a235d4f7eae19661d41bc154c

https://github.com/pborman/uuid

Code

package main

import (
	"fmt"
	"strings"

	"github.com/pborman/uuid"
)

func main() {
	uuidWithHyphen := uuid.NewRandom()
	fmt.Println(uuidWithHyphen)
	uuid := strings.Replace(uuidWithHyphen.String(), "-", "", -1)
	fmt.Println(uuid)
}

Output:

cda6498a-235d-4f7e-ae19-661d41bc154c
cda6498a235d4f7eae19661d41bc154c