### Install rs/xid Go Package Source: https://github.com/rs/xid/blob/master/README.md Instructions to install the rs/xid Go package using the go get command. This is the standard method for obtaining Go packages. ```go go get github.com/rs/xid ``` -------------------------------- ### Generate New Unique ID in Go Source: https://context7.com/rs/xid/llms.txt Demonstrates how to generate a new, globally unique ID using the xid.New() function. It shows how to get the string representation and generate multiple unique IDs in a loop. ```go package main import ( "fmt" "github.com/rs/xid" ) func main() { // Generate a new unique ID id := xid.New() // Get string representation (20 chars, base32hex encoded) fmt.Println(id.String()) // Output: 9m4e2mr0ui3e8a215n4g // Generate multiple IDs - all guaranteed unique for i := 0; i < 5; i++ { fmt.Println(xid.New().String()) } } ``` -------------------------------- ### SQL Database Integration with Go Source: https://context7.com/rs/xid/llms.txt Shows how xid.ID implements the database/sql Scanner and driver.Valuer interfaces, enabling direct use with SQL databases. This allows for inserting xids into database columns and scanning them back into Go variables without manual conversion. The example uses PostgreSQL, but it's applicable to other drivers. ```go package main import ( "database/sql" "fmt" "github.com/rs/xid" _ "github.com/lib/pq" // or any other driver ) type Record struct { ID xid.ID Data string } func main() { db, err := sql.Open("postgres", "connection-string") if err != nil { panic(err) } defer db.Close() // Insert with xid id := xid.New() _, err = db.Exec("INSERT INTO records (id, data) VALUES ($1, $2)", id, "test data") if err != nil { panic(err) } // Query and scan xid var record Record err = db.QueryRow("SELECT id, data FROM records WHERE id = $1", id).Scan(&record.ID, &record.Data) if err != nil { panic(err) } fmt.Println("Retrieved ID:", record.ID.String()) // Handle NULL values var nullableID xid.ID err = db.QueryRow("SELECT id FROM records WHERE id IS NULL").Scan(&nullableID) if nullableID.IsNil() { fmt.Println("ID is NULL") } } ``` -------------------------------- ### Generate and Format XID in Go Source: https://github.com/rs/xid/blob/master/README.md Demonstrates how to generate a new XID using `xid.New()` and convert it to its string representation. The output is a unique identifier. ```go guid := xid.New() println(guid.String()) // Output: 9m4e2mr0ui3e8a215n4g ``` -------------------------------- ### Benchmark XID vs UUID in Go Source: https://github.com/rs/xid/blob/master/README.md Presents benchmark results comparing the performance of rs/xid against satori/go.uuid. The benchmarks measure operations per second (ns/op), bytes per operation (B/op), and allocations per operation (allocs/op). ```text BenchmarkXID 20000000 91.1 ns/op 32 B/op 1 allocs/op BenchmarkXID-2 20000000 55.9 ns/op 32 B/op 1 allocs/op BenchmarkXID-4 50000000 32.3 ns/op 32 B/op 1 allocs/op BenchmarkUUIDv1 10000000 204 ns/op 48 B/op 1 allocs/op BenchmarkUUIDv1-2 10000000 160 ns/op 48 B/op 1 allocs/op BenchmarkUUIDv1-4 10000000 195 ns/op 48 B/op 1 allocs/op BenchmarkUUIDv4 1000000 1503 ns/op 64 B/op 2 allocs/op BenchmarkUUIDv4-2 1000000 1427 ns/op 64 B/op 2 allocs/op BenchmarkUUIDv4-4 1000000 1452 ns/op 64 B/op 2 allocs/op ``` -------------------------------- ### Check for Nil or Zero ID in Go Source: https://context7.com/rs/xid/llms.txt Illustrates how to check if an xid.ID is the zero value (nil ID) using the IsNil() and IsZero() methods. It also shows how to obtain a zero-value ID using xid.NilID(). ```go package main import ( "fmt" "github.com/rs/xid" ) func main() { var nilID xid.ID validID := xid.New() fmt.Println("Nil ID is nil:", nilID.IsNil()) fmt.Println("Nil ID is zero:", nilID.IsZero()) // alias fmt.Println("Valid ID is nil:", validID.IsNil()) // NilID() returns a zero-value ID zeroID := xid.NilID() fmt.Println("NilID() is nil:", zeroID.IsNil()) } ``` -------------------------------- ### Extract ID Components in Go Source: https://context7.com/rs/xid/llms.txt Demonstrates how to extract the embedded timestamp, machine identifier, process ID, and counter from an xid.ID object using its methods. ```go package main import ( "fmt" "github.com/rs/xid" ) func main() { id := xid.New() // Extract timestamp (1-second precision) fmt.Println("Time:", id.Time()) // Extract machine ID (3 bytes) fmt.Printf("Machine ID: %x\n", id.Machine()) // Extract process ID fmt.Println("PID:", id.Pid()) // Extract counter value fmt.Println("Counter:", id.Counter()) // Output example: // Time: 2024-01-15 14:30:45 +0000 UTC // Machine ID: a1b2c3 // PID: 12345 // Counter: 8421567 } ``` -------------------------------- ### Create ID from Byte Slice in Go Source: https://context7.com/rs/xid/llms.txt Explains how to create an xid.ID from a 12-byte slice using xid.FromBytes(). This is useful for scenarios involving binary storage or retrieval of IDs. It also shows error handling for incorrect byte lengths. ```go package main import ( "fmt" "github.com/rs/xid" ) func main() { // Create ID from bytes original := xid.New() bytes := original.Bytes() // Reconstruct from bytes restored, err := xid.FromBytes(bytes) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Original:", original.String()) fmt.Println("Restored:", restored.String()) fmt.Println("Equal:", original.Compare(restored) == 0) // Output: // Original: [same ID] // Restored: [same ID] // Equal: true // Invalid byte length returns error _, err = xid.FromBytes([]byte{1, 2, 3}) // wrong length if err == xid.ErrInvalidID { fmt.Println("Error: byte slice must be exactly 12 bytes") } } ``` -------------------------------- ### Extract Embedded Information from XID in Go Source: https://github.com/rs/xid/blob/master/README.md Shows how to retrieve embedded information such as the machine ID, process ID, timestamp, and counter from an existing XID object. This allows for inspection of the XID's components. ```go guid.Machine() guid.Pid() guid.Time() guid.Counter() ``` -------------------------------- ### Generate ID with Custom Timestamp in Go Source: https://context7.com/rs/xid/llms.txt Shows how to create a unique ID with a specific timestamp using xid.NewWithTime(). This is useful for generating IDs that need to be sorted according to a predefined time. ```go package main import ( "fmt" "time" "github.com/rs/xid" ) func main() { // Generate ID with a specific timestamp pastTime := time.Date(2023, 6, 15, 10, 30, 0, 0, time.UTC) id := xid.NewWithTime(pastTime) fmt.Println("ID:", id.String()) fmt.Println("Embedded time:", id.Time()) // Output: // ID: [20-char ID] // Embedded time: 2023-06-15 10:30:00 +0000 UTC } ``` -------------------------------- ### Manual Base32hex Encoding of IDs in Go Source: https://context7.com/rs/xid/llms.txt Provides a method for manually encoding an xid.ID into a provided byte buffer. This is useful for custom serialization scenarios, such as embedding IDs within larger byte structures or optimizing for performance by avoiding allocations in hot code paths. The buffer must be at least 20 bytes long. ```go package main import ( "fmt" "github.com/rs/xid" ) func main() { id := xid.New() // Encode into a pre-allocated buffer (must be at least 20 bytes) buf := make([]byte, 20) encoded := id.Encode(buf) fmt.Println("Encoded:", string(encoded)) fmt.Println("Buffer reused:", &buf[0] == &encoded[0]) // true // Useful for avoiding allocations in hot paths // or when embedding ID in larger byte structures } ``` -------------------------------- ### Parse ID from String in Go Source: https://context7.com/rs/xid/llms.txt Demonstrates parsing a base32hex encoded ID string back into an xid.ID object using xid.FromString(). Includes error handling for invalid ID formats. ```go package main import ( "fmt" "github.com/rs/xid" ) func main() { // Parse a valid ID string id, err := xid.FromString("9m4e2mr0ui3e8a215n4g") if err != nil { fmt.Println("Invalid ID:", err) return } fmt.Println("Parsed ID:", id.String()) fmt.Println("Timestamp:", id.Time()) // Handling invalid IDs _, err = xid.FromString("invalid") if err == xid.ErrInvalidID { fmt.Println("Error: invalid ID format") } // Output: Error: invalid ID format } ``` -------------------------------- ### Binary Storage with xidb Subpackage in Go Source: https://context7.com/rs/xid/llms.txt Utilizes the `b` subpackage for binary storage of xids, which is optimized for databases. This method stores IDs as 12-byte binary data instead of the standard 20-character base32hex string, potentially saving space and improving performance in database contexts. ```go package main import ( "database/sql" "fmt" "github.com/rs/xid" "github.com/rs/xid/b" ) func main() { db, _ := sql.Open("postgres", "connection-string") defer db.Close() // Create binary ID wrapper id := xidb.ID{ID: xid.New()} // Stores as 12-byte BYTEA instead of 20-char string _, err := db.Exec("INSERT INTO records (id) VALUES ($1)", id) if err != nil { panic(err) } // Scan binary data back var scannedID xidb.ID err = db.QueryRow("SELECT id FROM records LIMIT 1").Scan(&scannedID) if err != nil { panic(err) } fmt.Println("ID:", scannedID.ID.String()) } ``` -------------------------------- ### JSON Marshaling and Unmarshaling with Go Source: https://context7.com/rs/xid/llms.txt Demonstrates how xid.ID types automatically marshal to and unmarshal from JSON as base32hex strings. This allows for seamless integration with JSON APIs and data storage. Nil IDs are marshaled as JSON null values. ```go package main import ( "encoding/json" "fmt" "github.com/rs/xid" ) type User struct { ID xid.ID `json:"id"` Name string `json:"name"` } func main() { // Marshal to JSON user := User{ ID: xid.New(), Name: "John Doe", } data, err := json.Marshal(user) if err != nil { panic(err) } fmt.Println("JSON:", string(data)) // Output: {"id":"9m4e2mr0ui3e8a215n4g","name":"John Doe"} // Unmarshal from JSON jsonData := `{"id":"9m4e2mr0ui3e8a215n4g","name":"Jane Doe"}` var parsed User if err := json.Unmarshal([]byte(jsonData), &parsed); err != nil { panic(err) } fmt.Println("Parsed ID:", parsed.ID.String()) fmt.Println("Parsed Name:", parsed.Name) // Nil IDs marshal as null nilUser := User{Name: "No ID"} data, _ = json.Marshal(nilUser) fmt.Println("Nil ID JSON:", string(data)) // Output: {"id":null,"name":"No ID"} } ``` -------------------------------- ### Compare IDs Lexicographically using Go Source: https://context7.com/rs/xid/llms.txt Compares two xid.ID values lexicographically. Returns -1 if the first ID is less than the second, 0 if they are equal, and 1 if the first ID is greater than the second. This is useful for ordering IDs based on their creation time. ```go package main import ( "fmt" "time" "github.com/rs/xid" ) func main() { id1 := xid.New() time.Sleep(time.Millisecond) id2 := xid.New() result := id1.Compare(id2) switch result { case -1: fmt.Println("id1 < id2 (id1 was created first)") case 0: fmt.Println("id1 == id2") case 1: fmt.Println("id1 > id2 (id1 was created later)") } // Output: id1 < id2 (id1 was created first) } ``` -------------------------------- ### Set Machine ID via Environment Variable in Go Source: https://context7.com/rs/xid/llms.txt This Go code snippet demonstrates how to override the machine ID for xid generation by setting the XID_MACHINE_ID environment variable. The variable must be set before the `xid` package is initialized. The generated ID's machine component will reflect this setting. This is particularly useful in containerized environments where environment variables are commonly used for configuration. ```go package main import ( "fmt" "os" "github.com/rs/xid" ) func main() { // Set machine ID via environment (0 to 16777215) os.Setenv("XID_MACHINE_ID", "12345") // IDs generated will use this machine ID // Note: Must be set before package initialization id := xid.New() fmt.Printf("Machine ID: %x\n", id.Machine()) // In Docker/Kubernetes, set via deployment config: // env: // - name: XID_MACHINE_ID // value: "12345" } ``` -------------------------------- ### Sort Slice of IDs Chronologically using Go Source: https://context7.com/rs/xid/llms.txt Sorts a slice of xid.ID values in ascending chronological order. The sorting leverages the K-ordering property of xids, ensuring that IDs created earlier appear before those created later. This function modifies the slice in place. ```go package main import ( "fmt" "time" "github.com/rs/xid" ) func main() { // Create IDs with different timestamps ids := []xid.ID{ xid.NewWithTime(time.Now().Add(2 * time.Hour)), xid.NewWithTime(time.Now().Add(-1 * time.Hour)), xid.NewWithTime(time.Now()), } fmt.Println("Before sorting:") for _, id := range ids { fmt.Printf(" %s - %v\n", id.String(), id.Time()) } // Sort IDs (oldest first) xid.Sort(ids) fmt.Println("After sorting:") for _, id := range ids { fmt.Printf(" %s - %v\n", id.String(), id.Time()) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.