Go (Golang)

Go makes UUID generation easy with the popular google/uuid package, which provides RFC 4122 compliant UUID generation.

Using google/uuid Package (Recommended)

First, install the package:

go get github.com/google/uuid

Then use it in your code:

package main

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

func main() {
    // Generate a new UUID (version 4)
    id := uuid.New()
    fmt.Println(id.String())
    // Output: f47ac10b-58cc-4372-a567-0e02b2c3d479
}

Advanced Usage

package main

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

func main() {
    // Generate UUID v4 (random)
    id := uuid.New()
    fmt.Printf("UUID v4: %s\n", id.String())
    
    // Generate UUID v1 (time-based)
    id1, err := uuid.NewUUID()
    if err != nil {
        panic(err)
    }
    fmt.Printf("UUID v1: %s\n", id1.String())
    
    // Parse an existing UUID string
    parsed, err := uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
    if err != nil {
        panic(err)
    }
    fmt.Printf("Parsed: %s\n", parsed.String())
    
    // Generate UUID v5 (name-based with SHA-1)
    namespace := uuid.NameSpaceDNS
    id5 := uuid.NewSHA1(namespace, []byte("example.com"))
    fmt.Printf("UUID v5: %s\n", id5.String())
}

UUID as Struct Field

package main

import (
    "encoding/json"
    "fmt"
    "github.com/google/uuid"
)

type User struct {
    ID   uuid.UUID `json:"id"`
    Name string    `json:"name"`
}

func main() {
    user := User{
        ID:   uuid.New(),
        Name: "John Doe",
    }
    
    // Convert to JSON
    jsonData, _ := json.Marshal(user)
    fmt.Println(string(jsonData))
    // Output: {"id":"f47ac10b-58cc-4372-a567-0e02b2c3d479","name":"John Doe"}
}

Documentation: pkg.go.dev/github.com/google/uuid

*google/uuid package conforms to RFC 4122 UUID specification*