Skip to content

How to Generate UUID sequences in a GoLang?

GenerateUUID generates a new version 7 (random) UUID and returns it along with an error, if any.

The function returns a uuid.UUID and an error.

The version 7 UUID is generated using the random number generator and the node and clock sequences are generated based on the current time and the node's network interfaces, respectively.

If there is an error generating the UUID, the function returns a uuid.UUID{} (zero value) and the error.

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

func GenerateUUID() (uuid.UUID, error) {
	// Generate a new V7 (random) UUID
	generatedUUID, err := uuid.NewV7()
	if err != nil {
		// Return a zero value UUID and the error
		return uuid.UUID{}, err
	}
	// Return the generated UUID and nil error
	return generatedUUID, nil
}

Experience the magic of coding unfold as you execute this code!

package main

import (
	"fmt"

	"github.com/google/uuid"
)

func GenerateUUID() (uuid.UUID, error) {
	generatedUUID, err := uuid.NewV7()
	if err != nil {
		return uuid.UUID{}, err
	}
	return generatedUUID, nil
}

func main() {
	id, err := GenerateUUID()
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Println(id) // 0124e053-3580-7000-b00e-497f2c51d52b

	fmt.Println("Build with love by Adam Nasrudin")
}

enjoy your code!