### JavaScript Full Object Update Example Source: https://github.com/aarondl/opt/blob/master/README.md Illustrates a basic JavaScript example of fetching an object, mutating it, and then saving the entire object back to the API. This represents a full object update strategy. ```javascript let obj = getObjFromAPI(); // returns {"name":"hello", "age":5} obj.age = 6; // mutate the object saveObjToAPI(obj); // save the object ``` -------------------------------- ### Go Struct Initialization Examples Source: https://github.com/aarondl/opt/blob/master/README.md Demonstrates how a Go struct with an integer field is initialized. It shows explicit assignment and the use of the zero-value when no value is provided. ```go var e Example e = Example{Age: 5} // Explicit set to 5 e = Example{} // No value provided means 0-value takes over and age=0 ``` -------------------------------- ### JavaScript Partial Update Example Source: https://github.com/aarondl/opt/blob/master/README.md Shows a simplified JavaScript example of how partial updates are performed in an API context. This approach avoids the race conditions seen with full object updates by only sending the fields to be modified. ```javascript // clientA let obj = getObjFromAPI(); // returns {"name":"hello", "age":5} updateObjectInAPI({"age": 6}); // update object // clientB let obj = getObjFromAPI(); // returns {"name":"hello", "age":5} updateObjectInAPI({"name": "hi"}); // update object ``` -------------------------------- ### JavaScript Partial Update Conflict Example Source: https://github.com/aarondl/opt/blob/master/README.md Illustrates a JavaScript scenario where two clients attempt to partially update the same field ('age') concurrently. This demonstrates how partial updates handle conflicts predictably, with the last update prevailing. ```javascript // clientA let obj = getObjFromAPI(); // returns {"name":"hello", "age":5} updateObjectInAPI({"age": 6}); // update object // clientB let obj = getObjFromAPI(); // returns {"name":"hello", "age":5} updateObjectInAPI({"age": 7}); // update object ``` -------------------------------- ### JavaScript API Payloads for Partial Updates Source: https://github.com/aarondl/opt/blob/master/README.md Demonstrates different JavaScript object payloads used to signal intent for updating fields in an API request. These examples show how to set a value, set a value to null, or omit a field entirely, allowing for partial updates. ```javascript {"name": "hello", "age": 5} // set name = "hello", set age = 5, do not set other fields {"name": "hello", "age": null} // set name = "hello", set age = null, do not set other fields {"name": "hello"} // set name = "hello", do not set age, do not set other fields ``` -------------------------------- ### Database Integration with sql.Scanner and driver.Valuer in Go Source: https://context7.com/aarondl/opt/llms.txt The optional types in this library implement the `sql.Scanner` and `driver.Valuer` interfaces, enabling seamless integration with SQL databases. This allows for proper handling of NULL values from the database and correct serialization of optional values when inserting or updating records. The example demonstrates scanning nullable columns into Go structs and inserting/updating data with optional values. ```go package main import ( "database/sql" "fmt" "github.com/aarondl/opt/null" "github.com/aarondl/opt/omitnull" _ "github.com/lib/pq" ) type User struct { ID int Name string Age null.Val[int] Bio omitnull.Val[string] } func main() { db, _ := sql.Open("postgres", "postgres://localhost/mydb") // Scanning nullable columns var user User row := db.QueryRow("SELECT id, name, age, bio FROM users WHERE id = $1", 1) err := row.Scan(&user.ID, &user.Name, &user.Age, &user.Bio) if err != nil { panic(err) } // Check if age was NULL in database if user.Age.IsNull() { fmt.Println("Age not provided") } else { fmt.Println("Age:", user.Age.MustGet()) } // Insert with nullable values newUser := User{ Name: "Alice", Age: null.From(30), Bio: omitnull.Val[string]{}, // will insert as NULL } _, err = db.Exec( "INSERT INTO users (name, age, bio) VALUES ($1, $2, $3)", newUser.Name, newUser.Age, // driver.Valuer returns 30 newUser.Bio, // driver.Valuer returns nil (NULL) ) // Update with explicit NULL newUser.Age.Null() _, err = db.Exec( "UPDATE users SET age = $1 WHERE name = $2", newUser.Age, // sets age to NULL newUser.Name, ) } ``` -------------------------------- ### Working with omitnull.Val in Go Source: https://github.com/aarondl/opt/blob/master/README.md Demonstrates basic operations with `omitnull.Val`, including setting values, marking them as null or unset, and constructing new values from existing data or pointers. It also shows how to convert to other types and query the state of the optional value. ```go package main import ( "fmt" "github.com/aarondl/opt/omitnull" ) func main() { // Working with values that can be null or unset var val omitnull.Val[int] val.Set(5) // set the value to 5 fmt.Printf("Set to 5: %v\n", val) val.Null() // set the value to null fmt.Printf("Set to null: %v\n", val) val.Unset() // unset the value (omitted/undefined) fmt.Printf("Set to unset: %v\n", val) // Construct new values more directly val = omitnull.From(5) fmt.Printf("From 5: %v\n", val) // Example with FromPtr (requires a variable) // somePtr := new(int) // *somePtr = 10 // val = omitnull.FromPtr(somePtr) // fmt.Printf("From Ptr: %v\n", val) // Convert to other types // val.Ptr() // get a pointer back, will be nil if (null | unset). // Map function example mappedVal := omitnull.Map(val, func(i int) int { return i + 1 }) fmt.Printf("Mapped value: %v\n", mappedVal) // Query state val.Set(5) fmt.Printf("IsValue: %t, IsNull: %t, IsUnset: %t\n", val.IsValue(), val.IsNull(), val.IsUnset()) // Fetch the value out with varying levels of safety v, ok := val.Get() // returns (X, true) if the value is present if ok { fmt.Printf("Get value: %d\n", v) } v = val.GetOr(6) // returns 6 if no value is present fmt.Printf("GetOr 6: %d\n", v) // v = val.MustGet() // panics if no value is there // fmt.Printf("MustGet value: %d\n", v) // Convert between opt types (lossy, can panic) // val.MustGetNull() // val.MustGetOmit() // Converting between omitnull and other opt types // omitVal := omit.From(5) // nullVal := null.From(6) // fmt.Println(omitnull.FromNull(nullVal)) // fmt.Println(omitnull.FromOmit(omitVal)) // Converting between incompatible types (can panic or be incorrect) // o := omit.From(5) // n := null.From(6) // fmt.Println(null.From(o.MustGet())) // This panics when o == unset // fmt.Println(omit.From(n.MustGet())) // This panics when n == null // fmt.Println(null.FromBool(o.Get())) // This conflates null/omitted, technically incorrect // fmt.Println(omit.FromBool(n.Get())) // This conflates null/omitted, technically incorrect } ``` -------------------------------- ### JavaScript Race Condition with Full Updates Source: https://github.com/aarondl/opt/blob/master/README.md Presents a scenario in JavaScript demonstrating a race condition that can occur when multiple clients perform full object updates concurrently. This highlights the potential for lost updates. ```javascript // clientA let obj = getObjFromAPI(); // returns {"name":"hello", "age":5} obj.age = 6; // mutate the object saveObjToAPI(obj); // save the object // clientB let obj = getObjFromAPI(); // returns {"name":"hello", "age":5} obj.name = "hi"; // mutate the object saveObjToAPI(obj); // save the object ``` -------------------------------- ### Go Struct with Pointer to Integer Field Source: https://github.com/aarondl/opt/blob/master/README.md Defines a Go struct using a pointer to an integer to represent an optional field. This allows the field to be nil, indicating the absence of a value, which is common for SQL interoperability. ```go type ExampleNull struct { Age *int32 // or sql.NullInt32 } ``` -------------------------------- ### Go JSON Unmarshalling with Null Pointer Field Source: https://github.com/aarondl/opt/blob/master/README.md Demonstrates JSON unmarshalling into a Go struct with a pointer field when the JSON provides a 'null' value. The pointer field correctly becomes nil. ```go var e ExampleNull json.Unmarshal([]byte(`{"age":null}`), &e) ``` -------------------------------- ### Discriminated Union Types in Rust (Conceptual) Source: https://github.com/aarondl/opt/blob/master/README.md Illustrates the conceptual difference between nullable, omittable, and omittable-nullable types using Rust's enum syntax. This helps understand the distinct states each Opt type in Go represents. ```rust enum Nullable { Null, Value(T) } enum Omittable { Omitted, Value(T) } enum OmittableNullable { Omitted, Null, Value(T) } ``` -------------------------------- ### Go Struct with Integer Field Source: https://github.com/aarondl/opt/blob/master/README.md Defines a simple Go struct with an integer field. Go's zero-value mechanism ensures that this field always has a valid integer value, defaulting to 0 if not explicitly set. ```go type Example struct { Age int32 } ``` -------------------------------- ### Handle Nullable Values with Go's null.Val[T] Source: https://context7.com/aarondl/opt/llms.txt Demonstrates the usage of `null.Val[T]` for managing values that can be null or set, including creation, state querying, safe retrieval, mutation, and JSON marshaling/unmarshaling. This type is ideal for database fields and JSON properties where null is a distinct, valid state. ```go package main import ( "encoding/json" "fmt" "github.com/aarondl/opt/null" ) type User struct { Name string `json:"name"` Age null.Val[int] `json:"age"` } func main() { // Create null values var age null.Val[int] // zero value is null age = null.From(25) // set to 25 age = null.FromPtr[int](nil) // set to null from nil pointer age = null.FromCond(30, true) // conditionally set // Query state fmt.Println(age.IsValue()) // true if set fmt.Println(age.IsNull()) // true if null // Retrieve values safely if val, ok := age.Get(); ok { fmt.Println("Age:", val) } fmt.Println(age.GetOr(0)) // returns 0 if null fmt.Println(age.GetOrZero()) // returns zero value if null ptr := age.Ptr() // returns *int or nil // Mutate values age.Set(40) // set to 40 age.Null() // set to null var someInt int age.SetPtr(&someInt) // set from pointer // JSON marshaling - null values marshal as "null" user := User{Name: "Alice", Age: null.From(25)} data, _ := json.Marshal(user) fmt.Println(string(data)) // {"name":"Alice","age":25} user.Age.Null() data, _ = json.Marshal(user) fmt.Println(string(data)) // {"name":"Alice","age":null} // JSON unmarshaling json.Unmarshal([]byte(`{"name":"Bob","age":null}`), &user) fmt.Println(user.Age.IsNull()) // true } ``` -------------------------------- ### Go JSON Unmarshalling with Integer Field Source: https://github.com/aarondl/opt/blob/master/README.md Illustrates standard JSON unmarshalling into a Go struct with an integer field. This works as expected when the JSON provides a valid integer. ```go var e Example json.Unmarshal([]byte(`{"age":5}`), &e) ``` -------------------------------- ### Equal Function for Optional Value Comparison in Go Source: https://context7.com/aarondl/opt/llms.txt The 'Equal' function compares two optional values. It returns true if both values have the same state (set, null, or unset) and, if they are set, if their underlying values are equal. This function supports different optional types like null.Val, omit.Val, and omitnull.Val. ```go package main import ( "fmt" "github.com/aarondl/opt/null" "github.com/aarondl/opt/omit" "github.com/aarondl/opt/omitnull" ) func main() { // null.Val equality a := null.From(5) b := null.From(5) c := null.From(10) d := null.Val[int]{} // null fmt.Println(null.Equal(a, b)) // true (same value) fmt.Println(null.Equal(a, c)) // false (different values) fmt.Println(null.Equal(a, d)) // false (different states) fmt.Println(null.Equal(d, d)) // true (both null) // omit.Val equality x := omit.From("hello") y := omit.From("hello") z := omit.Val[string]{} // unset fmt.Println(omit.Equal(x, y)) // true fmt.Println(omit.Equal(x, z)) // false // omitnull.Val equality with three states p := omitnull.From(100) q := omitnull.From(100) r := omitnull.Val[int]{} // unset s := omitnull.Val[int]{} s.Null() // null fmt.Println(omitnull.Equal(p, q)) // true fmt.Println(omitnull.Equal(r, s)) // false (unset != null) fmt.Println(omitnull.Equal(s, s)) // true (both null) } ``` -------------------------------- ### Go JSON Unmarshalling with Missing Field Source: https://github.com/aarondl/opt/blob/master/README.md Illustrates JSON unmarshalling into a Go struct with a pointer field when the JSON object is missing the field entirely. The pointer field remains nil, similar to when 'null' is provided. ```go var e ExampleNull json.Unmarshal([]byte(`{}`), &e) ``` -------------------------------- ### omitnull.Val[T]: Three-State Values in Go Source: https://context7.com/aarondl/opt/llms.txt Demonstrates the usage of `omitnull.Val[T]` for representing values that can be unset, null, or set. It covers creation, state checking, retrieval, conversion, mutation, and JSON marshaling/unmarshaling for partial updates. ```go package main import ( "encoding/json" "fmt" "github.com/aarondl/opt/omitnull" "github.com/aarondl/opt/null" "github.com/aarondl/opt/omit" ) type PartialUpdate struct { Age omitnull.Val[int] `json:"age,omitzero"` Bio omitnull.Val[string] `json:"bio,omitzero"` } func main() { // Create values with three states var age omitnull.Val[int] // zero value is unset age = omitnull.From(25) // set to 25 age = omitnull.FromPtr[int](nil) // set to null // Convert from null.Val or omit.Val age = omitnull.FromNull(null.From(30)) age = omitnull.FromOmit(omit.From(35)) // Query all three states fmt.Println(age.IsValue()) // true if set to a value fmt.Println(age.IsNull()) // true if explicitly null fmt.Println(age.IsUnset()) // true if omitted/unset // Retrieve values if val, ok := age.Get(); ok { fmt.Println("Age:", val) } fmt.Println(age.GetOr(0)) // fallback for null or unset fmt.Println(age.GetOrZero()) // zero value for null or unset // Convert to null.Val or omit.Val (may panic if incompatible state) nullVal := age.MustGetNull() // panics if unset omitVal := age.MustGetOmit() // panics if null // Safe conversion with ok check if nv, ok := age.GetNull(); ok { fmt.Println("As nullable:", nv) } if ov, ok := age.GetOmit(); ok { fmt.Println("As omittable:", ov) } // Mutate to any state age.Set(40) // set to value age.Null() // set to null age.Unset() // set to unset var someInt int age.SetPtr(&someInt) // set from pointer (nil = null) // JSON partial update example update := PartialUpdate{ Age: omitnull.From(30), // set age to 30 // Bio is unset - will be omitted (don't update) } data, _ := json.Marshal(update) fmt.Println(string(data)) // {"age":30} // Set bio to null (clear the field) update.Bio.Null() data, _ = json.Marshal(update) fmt.Println(string(data)) // {"age":30,"bio":null} // Unmarshal handles all three states json.Unmarshal([]byte(`{"age":25}`), &update) fmt.Println(update.Age.IsValue()) // true fmt.Println(update.Bio.IsUnset()) // true (not in JSON) json.Unmarshal([]byte(`{"age":null}`), &update) fmt.Println(update.Age.IsNull()) // true } ``` -------------------------------- ### Or Method for Default Value Chaining in Go Source: https://context7.com/aarondl/opt/llms.txt The 'Or' method allows chaining optional values, returning the first value with a 'higher' state (set > null > unset). It's useful for providing fallback values when a primary optional value is not set or is null. This method is available for different optional types like null.Val and omitnull.Val. ```go package main import ( "fmt" "github.com/aarondl/opt/null" "github.com/aarondl/opt/omitnull" ) func main() { // null.Val Or - set > null primary := null.Val[int]{} // null fallback := null.From(42) result := primary.Or(fallback) fmt.Println(result.MustGet()) // 42 primary = null.From(10) result = primary.Or(fallback) fmt.Println(result.MustGet()) // 10 (primary wins when set) // omitnull.Val Or - set > null > unset val := omitnull.Val[string]{} // unset nullVal := omitnull.Val[string]{} nullVal.Null() // null setValue := omitnull.From("hello") // unset.Or(null) = null result2 := val.Or(nullVal) fmt.Println(result2.IsNull()) // true // unset.Or(set) = set result2 = val.Or(setValue) fmt.Println(result2.MustGet()) // "hello" // null.Or(set) = set result2 = nullVal.Or(setValue) fmt.Println(result2.MustGet()) // "hello" // set.Or(anything) = set result2 = setValue.Or(nullVal) fmt.Println(result2.MustGet()) // "hello" } ``` -------------------------------- ### Override JSON Marshaling with json-iterator in Go Source: https://context7.com/aarondl/opt/llms.txt Demonstrates how to override the default JSON marshaling and unmarshaling functions in the Opt package with the json-iterator library for improved performance. This allows all Opt types to utilize the custom JSON library for encoding and decoding. ```go package main import ( "github.com/aarondl/opt" "github.com/aarondl/opt/null" jsoniter "github.com/json-iterator/go" ) func init() { // Override with json-iterator for better performance var json = jsoniter.ConfigCompatibleWithStandardLibrary opt.JSONMarshal = json.Marshal opt.JSONUnmarshal = json.Unmarshal } func main() { // All opt types now use json-iterator val := null.From(map[string]int{"count": 42}) data, _ := val.MarshalJSON() // Uses json-iterator internally } ``` -------------------------------- ### Go JSON Unmarshalling with Null Integer Source: https://github.com/aarondl/opt/blob/master/README.md Shows the behavior of JSON unmarshalling when the JSON provides a 'null' value for an integer field in a Go struct. The integer field retains its zero-value (0) because 'null' cannot be assigned to an int32. ```go var e Example json.Unmarshal([]byte(`{"age": null}`), &e) ``` -------------------------------- ### TypeScript Interface with Optional Field Source: https://github.com/aarondl/opt/blob/master/README.md Defines a TypeScript interface representing an object with an 'age' field that can be undefined, null, or a number. This demonstrates TypeScript's flexibility in handling optional values. ```typescript interface Example { age: undefined | null | number; } ``` -------------------------------- ### Map Function: Transform Optional Values in Go Source: https://context7.com/aarondl/opt/llms.txt Illustrates the `Map` function for transforming the value within optional types (`null.Val`, `omit.Val`, `omitnull.Val`). It shows how the function preserves the state (set, null, or unset) of the original optional type. ```go package main import ( "fmt" "strings" "github.com/aarondl/opt/null" "github.com/aarondl/opt/omit" "github.com/aarondl/opt/omitnull" ) func main() { // Map method - same type transformation age := null.From(25) doubled := age.Map(func(v int) int { return v * 2 }) fmt.Println(doubled.MustGet()) // 50 nullAge := null.Val[int]{} // null stillNull := nullAge.Map(func(v int) int { return v * 2 }) fmt.Println(stillNull.IsNull()) // true (state preserved) // Map function - different type transformation name := omit.From("alice") upper := omit.Map(name, strings.ToUpper) fmt.Println(upper.MustGet()) // "ALICE" // Map with omitnull preserves all states val := omitnull.From(10) result := omitnull.Map(val, func(v int) string { return fmt.Sprintf("value: %d", v) }) fmt.Println(result.MustGet()) // "value: 10" val.Null() result = omitnull.Map(val, func(v int) string { return fmt.Sprintf("value: %d", v) }) fmt.Println(result.IsNull()) // true val.Unset() result = omitnull.Map(val, func(v int) string { return fmt.Sprintf("value: %d", v) }) fmt.Println(result.IsUnset()) // true } ``` -------------------------------- ### Manage Omittable Values with Go's omit.Val[T] Source: https://context7.com/aarondl/opt/llms.txt Illustrates the use of `omit.Val[T]` for handling values that can be unset or set, but never null. This is particularly useful for partial update APIs where distinguishing between an omitted field and a field explicitly set to a value is crucial. The zero value for this type is unset. ```go package main import ( "encoding/json" "fmt" "github.com/aarondl/opt/omit" ) type UpdateRequest struct { Name omit.Val[string] `json:"name,omitzero"` Email omit.Val[string] `json:"email,omitzero"` } func main() { // Create omittable values var name omit.Val[string] // zero value is unset name = omit.From("Alice") // set to "Alice" name = omit.FromPtr[string](nil) // unset from nil pointer name = omit.FromCond("Bob", false) // conditionally unset // Query state fmt.Println(name.IsValue()) // true if set fmt.Println(name.IsUnset()) // true if unset // Retrieve values safely if val, ok := name.Get(); ok { fmt.Println("Name:", val) } fmt.Println(name.GetOr("default")) // returns "default" if unset fmt.Println(name.GetOrZero()) // returns "" if unset // Mutate values name.Set("Charlie") // set value name.Unset() // mark as unset // IsZero for JSON omitzero support req := UpdateRequest{ Name: omit.From("NewName"), // Email is unset - will be omitted from JSON } data, _ := json.Marshal(req) fmt.Println(string(data)) // {"name":"NewName"} // Unmarshaling null into omit.Val returns an error err := json.Unmarshal([]byte(`{"name":null}`), &req) fmt.Println(err) // cannot unmarshal 'null' value into omit value } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.