Generate UUIDs in GO

Resources  |  Generate UUIDs in GO

Generating a UUID in Go can be done using a third-party package since the standard library does not include UUID generation functions. One of the most popular and widely used packages for this purpose is github.com/google/uuid.

Step-by-Step Guide to Generate a UUID in Go

  1. Install the UUID Package:

    First, you need to install the uuid package from Google. You can do this using go get.

    go get github.com/google/uuid
    
  2. Write the Go Code:

    Create a new Go file, for example, main.go, and use the uuid package to generate a UUID.

    package main
    
    import (
        "fmt"
        "github.com/google/uuid"
    )
    
    func main() {
        // Generate a new UUID
        newUUID := uuid.New()
    
        // Output the generated UUID
        fmt.Println("Generated UUID:", newUUID.String())
    }
    
  3. Run the Program:

    Save the file and run your Go program.

    go run main.go
    

Example Output

When you run the program, you should see an output similar to:

Generated UUID: 123e4567-e89b-12d3-a456-426614174000

Each time you run the program, a different UUID will be generated.

Full Example

Here is the complete process encapsulated in a concise form:

# Install the uuid package
go get github.com/google/uuid

# Create the main.go file with the following content:
cat <<EOL > main.go
package main

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

func main() {
    // Generate a new UUID
    newUUID := uuid.New()

    // Output the generated UUID
    fmt.Println("Generated UUID:", newUUID.String())
}
EOL

# Run the Go program
go run main.go

This script installs the necessary package, creates a Go file that generates a UUID, and then runs the Go program to display the generated UUID.

Explanation

  • go get github.com/google/uuid: This command installs the uuid package from Google.
  • import "github.com/google/uuid": This line imports the package into your Go program.
  • uuid.New(): This function generates a new UUID (version 4) using random numbers.
  • newUUID.String(): This method converts the UUID to its string representation.

By following these steps, you can easily generate UUIDs in your Go programs.