### Install gg Library Source: https://github.com/bytedance/gg/blob/main/README.md Use 'go get' to install the gg library. Ensure you are using Go 1.18 or later. ```sh go get github.com/bytedance/gg ``` -------------------------------- ### Quick Start: Stream Processing Example Source: https://github.com/bytedance/gg/blob/main/internal/stream/README.md Demonstrates constructing a stream from a slice, filtering zero values, and converting it back to a slice using method chaining. Evaluation occurs when ToSlice is called. ```go package main import ( "fmt" "github.com/bytedance/gg/gvalue" "github.com/bytedance/gg/internal/stream" ) func main() { s := stream.FromSlice([]int{0, 1, 2, 3, 4}). // Construct a stream from int slice Filter(gvalue.IsNotZero[int]). // Filter zero value lazily ToSlice() // Evaluate and convert back to slice fmt.Println(s) // Output: // [1 2 3 4] } ``` -------------------------------- ### gcond: Conditional Operation Examples Source: https://github.com/bytedance/gg/blob/main/README.md Demonstrates conditional logic using gcond. Includes examples for simple if-else, lazy evaluation of conditions, and a switch-like structure with cases, when conditions, and defaults. ```go import ( "github.com/bytedance/gg/gcond" ) gcond.If(true, 1, 2) // 1 var a *struct{ A int } getA := func() int { return a.A } get1 := func() int { return 1 } gcond.IfLazy(a != nil, getA, get1) // 1 gcond.IfLazyL(a != nil, getA, 1) // 1 gcond.IfLazyR(a == nil, 1, getA) // 1 gcond.Switch[string](3). Case(1, "1"). CaseLazy(2, func() string { return "3" }). When(3, 4).Then("3/4"). When(5, 6).ThenLazy(func() string { return "5/6" }). Default("other") // 3/4 ``` -------------------------------- ### gvalue: Zero Value Examples Source: https://github.com/bytedance/gg/blob/main/README.md Shows how to get the zero value for any type using gvalue.Zero and check if a value is its zero value using gvalue.IsZero. Also demonstrates gvalue.IsNil for pointer types and gvalue.Or for providing default values. ```go import ( "github.com/bytedance/gg/gvalue" ) a := gvalue.Zero[int]() // 0 gvalue.IsZero(a) // true b := gvalue.Zero[*int]() // nil gvalue.IsNil(b) // true gvalue.Or(0, 1, 2) // 1 ``` -------------------------------- ### goption: Option Type Examples Source: https://github.com/bytedance/gg/blob/main/README.md Demonstrates the usage of the goption type for handling optional values, simplifying the processing of (T, bool) pairs. Includes examples for creating, checking nil, providing default values, and mapping. ```go import ( "github.com/bytedance/gg/goption" "strconv" ) goption.Of(1, true).Value() // 1 goption.Nil[int]().IsNil() // true goption.Nil[int]().ValueOr(10) // 10 goption.OK(1).IsOK() // true goption.OK(1).ValueOrZero() // 1 goption.OfPtr((*int)(nil)).Ptr() // nil goption.Map(goption.OK(1), strconv.Itoa).Get() // "1" true ``` -------------------------------- ### gvalue: Math Operation Examples Source: https://github.com/bytedance/gg/blob/main/README.md Provides examples of generic mathematical operations using gvalue, including finding maximum, minimum, clamping values within a range, and performing addition. ```go import ( "github.com/bytedance/gg/gvalue" ) gvalue.Max(1, 2, 3) // 3 gvalue.Min(1, 2, 3) // 1 gvalue.MinMax(1, 2, 3) // 1 3 gvalue.Clamp(5, 1, 10) // 5 gvalue.Add(1, 2) // 3 ``` -------------------------------- ### gsync.Map Store Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Stores a key-value pair in a generic map. Ensure the map is initialized before storing. ```go import "github.com/bytedance/gg/gstd/gsync" sm := gsync.Map[string, int]{} sm.Store("key", 42) ``` -------------------------------- ### Tuple Creation and Usage Source: https://github.com/bytedance/gg/blob/main/README.md Provides examples of creating and using generic 2-element tuples (pairs) with Make2, Zip2, and Unzip. ```go addr := Make2("localhost", 8080) fmt.Printf("%s:%d\n", addr.First, addr.Second) // localhost:8080 s := Zip2([]string{"red", "green", "blue"}, []int{14, 15, 16}) for _, v := range s { fmt.Printf("%s:%d\n", v.First, v.Second) } // red:14 // green:15 // blue:16 s.Unzip() // ["red", "green", "blue"] [14, 15, 16] ``` -------------------------------- ### Import skipmap Package Source: https://github.com/bytedance/gg/blob/main/README.md Import the skipmap package to use its functionalities. This is the initial setup required for using the skipmap. ```go import ( "github.com/bytedance/gg/collection/skipmap" ) ``` -------------------------------- ### gsync.Pool Get Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Retrieves an object from the generic pool. If the pool is empty, it creates a new object using the `New` function. ```go pool := gsync.Pool[*int]{ New: func() *int { i := 0 return &i }, } obj := pool.Get() ``` -------------------------------- ### Partial Application Example Source: https://github.com/bytedance/gg/blob/main/gfunc/README.md Demonstrates how to use gfunc.Partial2 to create a partially applied function. The bound arguments can be reused, and all arguments can be fixed to produce a zero-arity function. ```go package main import ( "fmt" "github.com/bytedance/gg/gfunc" ) func main() { f := func(a, b int) int { return a + b } add := gfunc.Partial2(f) // Cast f to "partial application"-able function add1 := add.Partial(1) // Bind argument a to 1 fmt.Println(add1(0)) // 1 + 0 = 1 fmt.Println(add1(1)) // add1 can be reused, 1 + 1 = 2 add1n2 := add1.Partial(2) // Bind argument b to 2, all arguments are fixed fmt.Println(add1n2()) // 1 + 2 = 3 // Output: // 1 // 2 // 3 } ``` -------------------------------- ### gsync.Map LoadO Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Retrieves a value from the generic map as an optional type. Use `IsOK()` to check for presence and `Value()` to get the value. ```go opt := sm.LoadO("key") if opt.IsOK() { fmt.Println(opt.Value()) } ``` -------------------------------- ### gvalue: Comparison Examples Source: https://github.com/bytedance/gg/blob/main/README.md Demonstrates generic comparison functions provided by gvalue, specifically checking for equality and determining if a value falls within a specified range. ```go import ( "github.com/bytedance/gg/gvalue" ) gvalue.Equal(1, 1) // true gvalue.Between(2, 1, 3) // true ``` -------------------------------- ### Gcond If-Else Replacement Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Shows how to replace a traditional if-else block with the Gcond If function for concise conditional assignment. ```go // Traditional var result int if condition { result = 1 } else { result = 2 } // With gcond result := gcond.If(condition, 1, 2) ``` -------------------------------- ### gsync.Map ToMap Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Converts the generic map into a standard Go map. This creates a snapshot of the map's current state. ```go standardMap := sm.ToMap() // map[string]int{"key": 42} ``` -------------------------------- ### gsync.Map Load Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Retrieves a value from the generic map by key. Checks the boolean return to confirm if the key was present. ```go val, ok := sm.Load("key") if ok { fmt.Println(val) // 42 } ``` -------------------------------- ### gsync.OnceFunc Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Wraps a function to ensure it is executed only once, even if called multiple times. Subsequent calls will have no effect. ```go onceFunc := gsync.OnceFunc(func() { fmt.Println("This runs only once") }) onceFunc() onceFunc() // No output onceFunc() // No output ``` -------------------------------- ### Example of Then in Gcond Switch Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Illustrates using Then to set a string result for a When clause that matches either 1 or 2. If no other cases match, the Default is used. ```go gcond.Switch[string](2). When(1, 2).Then("One or Two"). Default("Other") // "One or Two" ``` -------------------------------- ### Example of When, Then, and Default in Gcond Switch Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Shows a switch statement using When to match multiple values, Then to provide a result, and Default for a fallback. The first matching When clause determines the result. ```go result := gcond.Switch[string](1). When(1, 2).Then("One"). When(3, 4).Then("Three"). Default("Other") // "One" ``` -------------------------------- ### Quick Start: Iterating, Filtering, and Mapping a Slice Source: https://github.com/bytedance/gg/blob/main/internal/iter/README.md Demonstrates creating an iterator from a slice, filtering out zero values, converting integers to strings, and collecting the results into a new slice. Evaluation is triggered by the 'ToSlice' sink. ```Go package main import ( "fmt" "strconv" "github.com/bytedance/gg/gvalue" "github.com/bytedance/gg/internal/iter" ) func main() { s := iter.ToSlice( iter.Map(strconv.Itoa, iter.Filter(gvalue.IsZero[int], iter.FromSlice([]int{0, 1, 2, 3, 4})) وبركاته fmt.Printf("%q\n", s) // Output: // ["1" "2" "3" "4"] } ``` -------------------------------- ### Gcond Complex Matching Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Illustrates a complex switch statement using When, Then, and Default to handle multiple user roles and assign corresponding access levels. ```go result := gcond.Switch[string](userRole). When("admin", "superuser").Then("Full Access"). When("user", "guest").Then("Limited Access"). When("anonymous").Then("No Access"). Default("Unknown Role") ``` -------------------------------- ### gcond.Switch and Case Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Use gcond.Switch and its Case method to build flexible switch statements. This pattern allows chaining cases and defining a default value. ```Go result := gcond.Switch[string](1). Case(1, "One"). Case(2, "Two"). Default("Other") // "One" ``` ```Go gcond.Switch[string](1). Case(1, "One"). Case(2, "Two"). Default("Other") // "One" ``` -------------------------------- ### Get the first element of the list Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-list.md Retrieves the first element in the list. Returns nil if the list is empty. ```go func (l *List[T]) Front() *Element[T] ``` ```go l := list.New[int]() e1 := l.PushFront(1) l.Front() // e1 ``` -------------------------------- ### Initiate Multi-Value Case Statement Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Starts a multi-value case in a switch statement. This must be followed by Then or ThenLazy to define the result. ```go func (s *switchBuilder[R, T]) When(values ...T) *whenClause[R, T] ``` -------------------------------- ### gsync.Pool Put Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Returns an object to the generic pool for potential reuse. The object must have been previously obtained from the same pool. ```go obj := pool.Get() // Use obj... pool.Put(obj) ``` -------------------------------- ### Partial Application with Higher-Order Functions Source: https://github.com/bytedance/gg/blob/main/internal/iter/README.md Utilizes partial application to simplify the use of higher-order functions like Map. This example demonstrates creating a specialized 'add1' function by binding the first argument of a generic Add function, then applying it to a slice of integers. ```go add := gvalue.Add[int] // instantiate a int version of Add function add1 := gfunc.Partial2(add).Partial(1) // bind the first argument to 1 s := ToSlice( Map(add1, FromSlice([]int{1, 2, 3, 4}))) fmt.Println(s) ``` -------------------------------- ### Concurrent Store Operations in skipmap Source: https://github.com/bytedance/gg/blob/main/README.md Illustrates concurrent storage of elements into the skipmap using goroutines. This example shows how to handle a large number of concurrent writes safely. ```go var wg sync.WaitGroup wg.Add(1000) for i := 0; i < 1000; i++ { i := i go func() { defer wg.Done() s.Store(strconv.Itoa(i), i) }() } wg.Wait() s.Len() // 1000 ``` -------------------------------- ### gsync.Map LoadAndDelete Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Retrieves a value associated with a key and then deletes the key-value pair from the map. Returns the value and a boolean indicating if the key was found. ```go val, ok := sm.LoadAndDelete("key") if ok { fmt.Println("Deleted", val) } ``` -------------------------------- ### gsync.Map LoadOrStore Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Loads a value if the key exists, otherwise stores the provided value. Returns the loaded or stored value and a boolean indicating if it was loaded (true) or stored (false). ```go val, loaded := sm.LoadOrStore("key", 42) ``` -------------------------------- ### gcond.IfLazy Function Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Use gcond.IfLazy when you need lazy evaluation of both potential results. This prevents unnecessary computation or panics if a value is not needed. ```Go v1 := func() int { return 1 } v2 := func() int { return 2 } vp := func() int { panic("error") } gcond.IfLazy(true, v1, v2) // 1 (v2 not called) gcond.IfLazy(true, v1, vp) // 1 (vp not called, no panic) gcond.IfLazy(false, vp, v2) // 2 (vp not called, no panic) ``` -------------------------------- ### Gcond Lazy Evaluation Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Demonstrates using Gcond IfLazy for conditional logic where the results are computed lazily. This avoids unnecessary computation for the non-selected branch. ```go // Avoids unnecessary computation result := gcond.IfLazy(condition, func() string { return expensiveComputation() }, func() string { return defaultValue() }) ``` -------------------------------- ### Example of Default in Gcond Switch Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Shows a switch statement where the input value 5 does not match the Case(1), so the Default result 'Other' is returned. This demonstrates the fallback mechanism. ```go result := gcond.Switch[string](5). Case(1, "One"). Default("Other") // "Other" ``` -------------------------------- ### Get Value and Error Tuple Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gresult.md The Get method returns the result as a standard Go (value, error) tuple, making it compatible with idiomatic Go error handling. ```go v, err := gresult.OK(42).Get() // 42, nil v, err := gresult.Err[int](e).Get() // 0, error ``` -------------------------------- ### Example of CaseLazy in Gcond Switch Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Demonstrates using CaseLazy to add a case with a lazily evaluated string result. The function is called only if the input matches the case value. ```go gcond.Switch[string](1). CaseLazy(1, func() string { return "One" }). Default("Other") // "One" ``` -------------------------------- ### Configuration Functions with Partial Binding Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Illustrates using partial binding to create specialized configuration functions, such as a logger with a pre-set log level. ```go // Create a configured logger newLog := gfunc.Partial2(func(level, msg string) string { return fmt.Sprintf("[%s] %s", level, msg) }) infoLog := newLog.Partial("INFO") infoLog("System started") // "[INFO] System started" ``` -------------------------------- ### Validate JSON and Handle Unmarshal Errors Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gson.md Provides examples for validating JSON data before unmarshaling and safely handling potential errors during the unmarshaling process. Also shows how to convert data to string, ignoring errors. ```go // Validate JSON before unmarshaling if !gson.Valid(jsonBytes) { fmt.Println("Invalid JSON") return } // Safe unmarshaling result, err := gson.UnmarshalBy[MyType](codec, jsonBytes) if err != nil { fmt.Printf("Unmarshal failed: %v\n", err) } // Ignore errors str := gson.ToString(data) // Returns empty string on error ``` -------------------------------- ### gsync.Map Delete Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Removes a key and its associated value from the generic map. ```go sm.Delete("key") ``` -------------------------------- ### Get Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gslice.md Retrieves an element from a slice at a specified index. Supports negative indices for Python-style access. ```APIDOC ## Get ### Description Retrieves an element from a slice at a specified index. Supports negative indices (Python-style). ### Signature ```go func Get[T any, I constraints.Integer](s []T, n I) goption.O[T] ``` ### Parameters #### Path Parameters - **s** ([]T) - Required - Input slice - **n** (I) - Required - Index (supports negative) ### Return type `goption.O[T]` — Optional element. ### Example ```go gslice.Get([]int{1, 2, 3}, 1) // goption.OK(2) gslice.Get([]int{1, 2, 3}, -1) // goption.OK(3) gslice.Get([]int{1, 2, 3}, 10) // goption.Nil[int]() ``` ``` -------------------------------- ### Get Map Values Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gmap.md Retrieves all values from a map. The order of values in the returned slice is not guaranteed. ```go values := gmap.Values(map[string]int{"a": 1, "b": 2}) // []int (order not guaranteed) ``` -------------------------------- ### Create a 3-Tuple using Make3 Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-tuple.md Shows how to create a 3-tuple using the `Make3` constructor, suitable for returning three values. ```go rgb := tuple.Make3(255, 128, 0) ``` -------------------------------- ### Get Map Keys Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gmap.md Retrieves all keys from a map. The order of keys in the returned slice is not guaranteed. ```go keys := gmap.Keys(map[string]int{"a": 1, "b": 2}) // []string (order not guaranteed) ``` -------------------------------- ### Go Function Partial Application Source: https://github.com/bytedance/gg/blob/main/README.md Demonstrates partial application of functions, allowing arguments to be pre-bound. ```go import ( "github.com/bytedance/gg/gfunc" "github.com/bytedance/gg/gvalue" ) add := gfunc.Partial2(gvalue.Add[int]) // convert the Add function into a partial function add1 := add.Partial(1) // Bind (i.e., "freeze") the first argument to 1 add1(0) // 0 + 1 = 1 // 1 add1(1) // Reuse the partially applied function: 1 + 1 = 2 // 2 add1n2 := add1.PartialR(2) // Bind the remaining (rightmost) argument to 2; all arguments are now fixed add1n2() // 1 + 2 = 3 ``` -------------------------------- ### Get Map Length Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gmap.md Returns the number of entries in the map. This is a straightforward way to determine the size of a map. ```go func Len[K comparable, V any](m map[K]V) int gmap.Len(map[string]int{"a": 1, "b": 2}) // 2 ``` -------------------------------- ### Get the last element of the list Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-list.md Retrieves the last element in the list. Returns nil if the list is empty. ```go func (l *List[T]) Back() *Element[T] ``` ```go l := list.New[int]() l.PushFront(1) e2 := l.PushBack(2) l.Back() // e2 ``` -------------------------------- ### Reusable Operations with Partial Binding Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Demonstrates creating reusable, specialized operations like formatters by pre-binding common parameters using partial application. ```go // Create specialized formatters format := gfunc.Partial2(func(pattern, value string) string { return fmt.Sprintf(pattern, value) }) hexFormat := format.Partial("0x%x") hexFormat(255) // "0xff" decFormat := format.Partial("%d") decFormat(255) // "255" ``` -------------------------------- ### Callback Builders with Partial Binding Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Shows how to build callback functions with pre-bound context using partial application, simplifying error handling or event processing. ```go // Build callbacks with pre-bound context handleError := gfunc.Partial2(func(ctx, err string) { log.Printf("[%s] Error: %s\n", ctx, err) }) handleAPIError := handleError.Partial("API") handleAPIError("connection failed") ``` -------------------------------- ### Get Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gresult.md Returns the result in a (value, error) tuple, compatible with Go's idiomatic error handling pattern. ```APIDOC ## Get ### Description Returns the result in `(value, error)` form, compatible with Go's idiomatic pattern. ### Method Signature ```go func (r R[T]) Get() (T, error) ``` ### Return type `(T, error)` — The value and error. ### Example ```go v, err := gresult.OK(42).Get() // 42, nil v, err := gresult.Err[int](e).Get() // 0, error ``` ``` -------------------------------- ### Get Set Size Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-skipset.md Returns the number of elements currently in the set. Note that this count is approximate in concurrent contexts. ```go s := skipset.New[int]() s.Add(1) s.Add(2) s.Add(3) s.Len() // 3 ``` -------------------------------- ### Use Case: Configuration Functions Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Demonstrates using partial application to create specialized configuration functions, such as a logger with a pre-set log level. ```APIDOC ## Use Case: Configuration Functions ### Description Create configured functions by pre-binding configuration parameters. ### Example ```go // Create a configured logger newLog := gfunc.Partial2(func(level, msg string) string { return fmt.Sprintf("[%s] %s", level, msg) }) infoLog := newLog.Partial("INFO") infoLog("System started") // "[INFO] System started" ``` ``` -------------------------------- ### gsync.OnceFunc and OnceValue Usage Source: https://github.com/bytedance/gg/blob/main/README.md Shows how to use gsync.OnceFunc for executing a function exactly once and gsync.OnceValue for computing and returning a value exactly once. ```go onceFunc := gsync.OnceFunc(func() { fmt.Println("OnceFunc") }) onceFunc() // "OnceFunc" onceFunc() // (no output) onceFunc() // (no output) i := 1 onceValue := gsync.OnceValue(func() int { i++; return i }) onceValue() // 2 onceValue() // 2 ``` -------------------------------- ### Get Last Element of Slice Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gslice.md Returns the last element of the slice as an optional value. Returns nil if the slice is empty. ```Go gslice.Last([]int{1, 2, 3}) // goption.OK(3) ``` -------------------------------- ### Get First Element of Slice Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gslice.md Returns the first element of the slice as an optional value. Returns nil if the slice is empty. ```Go gslice.First([]int{1, 2, 3}) // goption.OK(1) gslice.First([]int{}) // goption.Nil[int]() ``` -------------------------------- ### Get Sorted Map Keys Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gmap.md Retrieves keys from a map in sorted order. Requires keys to implement the constraints.Ordered interface. ```go keys := gmap.OrderedKeys(map[int]string{3: "c", 1: "a", 2: "b"}) // []int{1, 2, 3} ``` -------------------------------- ### Go Slice Partition Operations (gslice) Source: https://github.com/bytedance/gg/blob/main/README.md Demonstrates partition operations on slices, including creating ranges, taking elements, slicing, chunking, dividing, concatenating, flattening, and partitioning based on a predicate. ```go gslice.Range(1, 5) // [1, 2, 3, 4] gslice.RangeWithStep(5, 1, -2) // [5, 3] gslice.Take([]int{1, 2, 3, 4, 5}, 2) // [1, 2] gslice.Take([]int{1, 2, 3, 4, 5}, -2) // [4, 5] gslice.Slice([]int{1, 2, 3, 4, 5}, 1, 3) // [2, 3] gslice.Chunk([]int{1, 2, 3, 4, 5}, 2) // [[1, 2], [3, 4], [5]] gslice.Divide([]int{1, 2, 3, 4, 5}, 2) // [[1, 2, 3], [4, 5]] gslice.Concat([]int{1, 2}, []int{3, 4, 5}) // [1, 2, 3, 4, 5] gslice.Flatten([][]int{{1, 2}, {3, 4, 5}}) // [1, 2, 3, 4, 5] gslice.Partition([]int{1, 2, 3, 4, 5}, isEven) // [2, 4], [1, 3, 5] ``` -------------------------------- ### Define and Call a Nullary Function (Func0) Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Demonstrates how to define a nullary function (zero arguments, one return value) using gfunc.Func0 and how to invoke it. ```go import "github.com/bytedance/gg/gfunc" var f gfunc.Func0[int] = func() int { return 42 } result := f() // 42 ``` -------------------------------- ### Get Error or Nil Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gresult.md The Err method returns the contained error if the result is an error state, otherwise it returns nil. ```go e := gresult.OK(42).Err() // nil gresult.Err[int](errors.New("fail")).Err() // error ``` -------------------------------- ### Get the number of elements in the list Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-list.md Returns the total count of elements currently in the list. This operation has a constant time complexity. ```go func (l *List[T]) Len() int ``` ```go l := list.New[int]() l.PushFront(1) l.Len() // 1 ``` -------------------------------- ### Basic skipmap Operations Source: https://github.com/bytedance/gg/blob/main/README.md Demonstrates basic operations like storing, loading, deleting, and checking the length of the skipmap. It also shows how to load or store a value if the key does not exist. ```go s := New[string, int]() s.Store("a", 0) s.Store("a", 1) s.Store("b", 2) s.Store("c", 3) s.Len() // 3 s.Load("a") // 1 true s.LoadAndDelete("a") // 1 true s.LoadOrStore("a", 11) // 11 false gson.ToString(s.ToMap()) // {"a":11, "b":2, "c": 3} s.Delete("a") s.Delete("b") s.Delete("c") ``` -------------------------------- ### Get the number of elements in a Set Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-set.md The `Len` method returns the current count of elements in the set. This operation has O(1) complexity. ```go s := set.New(1, 2, 3) s.Len() // 3 ``` -------------------------------- ### Import gsync Package Source: https://github.com/bytedance/gg/blob/main/README.md Import the gsync package to use its wrappers for standard Go concurrency primitives. ```go import ( "github.com/bytedance/gg/gstd/gsync" ) ``` -------------------------------- ### Create a 2-Tuple using Make2 Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-tuple.md Demonstrates creating a 2-tuple using the `Make2` constructor. This is useful for returning multiple values from a function. ```go import "github.com/bytedance/gg/collection/tuple" addr := tuple.Make2("localhost", 8080) fmt.Printf("%s:%d\n", addr.First, addr.Second) ``` -------------------------------- ### gcond.IfLazyR Function Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Use gcond.IfLazyR when only the 'onFalse' value needs lazy evaluation. The 'onTrue' value is evaluated immediately. ```Go gcond.IfLazyR(true, 1, func() int { return 2 }) // 1 gcond.IfLazyR(false, 1, func() int { return 2 }) // 2 ``` -------------------------------- ### Import skipset Package Source: https://github.com/bytedance/gg/blob/main/README.md Import the skipset package to use its high-performance, concurrent-safe set implementation based on skip lists. ```go import ( "github.com/bytedance/gg/collection/skipset" ) ``` -------------------------------- ### gcond.IfLazyL Function Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Use gcond.IfLazyL when only the 'onTrue' value needs lazy evaluation. The 'onFalse' value is evaluated immediately. ```Go gcond.IfLazyL(true, func() int { return 1 }, 2) // 1 gcond.IfLazyL(false, func() int { return 1 }, 2) // 2 ``` -------------------------------- ### Create a new empty list Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-list.md Initializes and returns a new, empty doubly linked list. The zero value of the list is ready for use. ```go func New[T any]() *List[T] ``` ```go l := list.New[int]() ``` -------------------------------- ### Get String Representation Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gresult.md Returns a string representation of the result, indicating whether it's an OK value or an error. Useful for debugging. ```Go fmt.Println(gresult.OK(42)) // gresult.OK[int](42) fmt.Println(gresult.Err[int](err)) // gresult.Err[int](...) ``` -------------------------------- ### Object Pooling with gsync.Pool Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gsync.md Implements an object pool for byte slices using gsync.Pool. Shows how to initialize the pool with a New function and manage object retrieval and return. ```go type bufferPool struct { pool gsync.Pool[[]byte] } func newBufferPool() *bufferPool { return &bufferPool{ pool: gsync.Pool[[]byte]{ New: func() []byte { return make([]byte, 0, 1024) }, }, } } func (bp *bufferPool) get() []byte { return bp.pool.Get() } func (bp *bufferPool) put(buf []byte) { buf = buf[:0] // Reset to empty bp.pool.Put(buf) } ``` -------------------------------- ### Set Operations Source: https://github.com/bytedance/gg/blob/main/README.md Demonstrates common set operations including adding, removing, checking for elements, and converting to a slice. ```go s := New(10, 10, 12, 15) s.Len() // 3 s.Add(10) // false s.Add(11) // true s.Remove(11) && s.Remove(12) // true s.ContainsAny(10, 15) // true s.ContainsAny(11, 12) // false s.ContainsAny() // false s.ContainsAll(10, 15) // true s.ContainsAll(10, 11) // false s.ContainsAll() // true len(s.ToSlice()) // 2 ``` -------------------------------- ### Get Value or Fallback Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gresult.md The ValueOr method returns the contained value if the result is OK, otherwise it returns the provided fallback value. ```go gresult.OK(42).ValueOr(100) // 42 gresult.Err[int](err).ValueOr(100) // 100 ``` -------------------------------- ### Transpose Data using Zip2 and Unzip Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-tuple.md Demonstrates transposing data by first zipping related data into pairs and then using `Unzip` to separate them, effectively transforming columns to rows. ```go // Unzip transforms columns to rows type Person struct { Name string Age int } names := []string{"Alice", "Bob"} ages := []int{30, 25} // Combine into pairs pairs := tuple.Zip2(names, ages) // Each pair.First is a name, pair.Second is an age for _, pair := range pairs { fmt.Printf("%s is %d\n", pair.First, pair.Second) } ``` -------------------------------- ### Get the previous element in the list Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-list.md Retrieves the preceding element in the linked list. Returns nil if the current element is the first one. ```go func (e *Element[T]) Prev() *Element[T] ``` ```go l := list.New[int]() e1 := l.PushFront(1) e2 := l.PushBack(2) prev := e2.Prev() // e1 ``` -------------------------------- ### Marshal and Unmarshal with Standard Library Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gson.md Demonstrates encoding Go structs to JSON bytes and strings, and decoding JSON bytes back into Go structs using the standard library. ```go import "github.com/bytedance/gg/gson" // Encoding data := struct { Name string `json:"name"` Age int `json:"age"` }{ Name: "Alice", Age: 30, } bytes, err := gson.Marshal(data) str, err := gson.MarshalString(data) // Decoding var decoded struct{} gson.Unmarshal[struct{}](bytes) ``` -------------------------------- ### Get the next element in the list Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-list.md Retrieves the subsequent element in the linked list. Returns nil if the current element is the last one. ```go func (e *Element[T]) Next() *Element[T] ``` ```go import "github.com/bytedance/gg/collection/list" l := list.New[int]() e1 := l.PushFront(1) e2 := l.PushBack(2) next := e1.Next() // e2 ``` -------------------------------- ### List.New Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-list.md Creates and returns an initialized empty doubly linked list. ```APIDOC ## List.New ### Description Creates and returns an initialized empty list. ### Constructor ```go func New[T any]() *List[T] ``` ### Return Value * **List[T]** - A new, empty list. ### Example ```go l := list.New[int]() ``` ``` -------------------------------- ### Get Internal Value of Optional Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/goption.md Retrieves the internal value of the optional. If the optional is empty, it returns the zero value of the type T. ```go goption.OK(42).Value() // 42 goption.Nil[int]().Value() // 0 ``` -------------------------------- ### Chained Partial Application of Ternary Function (Func3) Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Shows how to sequentially bind arguments of a ternary function (Func3) using multiple Partial calls. Each call reduces the number of arguments for the resulting function. ```go concat := func(a, b, c string) string { return a + b + c } f := gfunc.Partial3(concat) withHello := f.Partial("Hello") withWorld := withHello.Partial(" World") result := withWorld(" Go") // "Hello World Go" ``` -------------------------------- ### Partial Application of Binary Function (Func2) - Right Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Demonstrates binding the second argument of a binary function (Func2) using the PartialR method. This also returns a unary function (Func1) with the remaining argument. ```go divide := func(x, y int) int { return x / y } f := gfunc.Partial2(divide) divideBy2 := f.PartialR(2) // Binds second argument to 2 result := divideBy2(10) // 5 ``` -------------------------------- ### gcond.If Function Example Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Use gcond.If for a direct replacement of ternary operators. Note that both onTrue and onFalse arguments are always evaluated. ```Go import "github.com/bytedance/gg/gcond" gcond.If(true, 1, 2) // 1 gcond.If(false, 1, 2) // 2 ``` -------------------------------- ### Get Element from Slice Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gslice.md Retrieves an element from a slice at a specified index. Supports negative indices for Python-style access. Returns an optional element. ```go gslice.Get([]int{1, 2, 3}, 1) // goption.OK(2) gslice.Get([]int{1, 2, 3}, -1) // goption.OK(3) gslice.Get([]int{1, 2, 3}, 10) // goption.Nil[int]() ``` -------------------------------- ### Partial Application of Binary Function (Func2) - Left Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Illustrates binding the first argument of a binary function (Func2) using the Partial method. This returns a unary function (Func1) with the remaining argument. ```go add := func(x, y int) int { return x + y } f := gfunc.Partial2(add) add5 := f.Partial(5) // Binds first argument to 5 result := add5(3) // 8 ``` -------------------------------- ### Get Zero Value of a Type Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gvalue.md Returns the zero value for any given type T. This is useful for initializing variables or ensuring a default state. ```go import "github.com/bytedance/gg/gvalue" gvalue.Zero[int]() // 0 gvalue.Zero[string]() // "" gvalue.Zero[*int]() // nil ``` -------------------------------- ### Get Values by Sorted Keys Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gmap.md Retrieves values from a map ordered by their corresponding sorted keys. Requires keys to implement the constraints.Ordered interface. ```go values := gmap.OrderedValues(map[int]string{3: "c", 1: "a", 2: "b"}) // []string{"a", "b", "c"} ``` -------------------------------- ### Partial Application of Unary Function (Func1) Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Shows how to use the Partial method on a unary function (Func1) to bind its single argument, resulting in a nullary function (Func0). This is useful for creating specialized functions. ```go add1 := func(x int) int { return x + 1 } f1 := gfunc.Partial1(add1) addSpecific := f1.Partial(5) // Binds the argument result := addSpecific() // 6 ``` -------------------------------- ### Represent 2D Points and RGB Colors with Tuples Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-tuple.md Illustrates using `Make2` for 2D points and `Make3` for RGB color values, showcasing tuples for coordinate and color representation. ```go // 2D point point := tuple.Make2(10.5, 20.3) x, y := point.First, point.Second // RGB color color := tuple.Make3(255, 128, 0) r, g, b := color.First, color.Second, color.Third ``` -------------------------------- ### Get Internal Value or Fallback Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/goption.md Returns the internal value if present, otherwise returns a specified fallback value. Useful for providing defaults. ```go goption.OK(42).ValueOr(100) // 42 goption.Nil[int]().ValueOr(100) // 100 ``` -------------------------------- ### Get Number of Elements in Skip Map Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-skipmap.md Returns the current count of key-value pairs in the map. Note that this count is approximate in concurrent contexts. ```go m := skipmap.New[string, int]() m.Store("a", 1) m.Store("b", 2) m.Len() // 2 ``` -------------------------------- ### New Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-skipset.md Creates a new, empty skip list set. The type of elements in the set must be ordered. ```APIDOC ## New Creates a new skip list set. ### Signature ```go func New[T constraints.Ordered]() *Set[T] ``` ### Parameters This function does not take any parameters. ### Return Value - `*Set[T]`: A pointer to the newly created, empty skip list set. ### Example ```go import "github.com/bytedance/gg/collection/skipset" s := skipset.New[int]() ``` ``` -------------------------------- ### Import list Package Source: https://github.com/bytedance/gg/blob/main/README.md Import the list package for using a generic doubly linked list implementation. ```go import ( "github.com/bytedance/gg/collection/list" ) ``` -------------------------------- ### gsync.Map Usage Source: https://github.com/bytedance/gg/blob/main/README.md Demonstrates the usage of gsync.Map, a generic wrapper around sync.Map, for concurrent-safe key-value storage. ```go sm := gsync.Map[string, int]{} sm.Store("k", 1) sm.Load("k") // 1 true sm.LoadO("k").Value() // 1 sm.Store("k", 2) sm.Load("k") // 2 true sm.LoadAndDelete("k") // 2 true sm.Load("k") // 0 false sm.LoadOrStore("k", 3) // 3 false sm.Load("k") // 3 true sm.ToMap() // {"k":3} ``` -------------------------------- ### Go Slice to Map Conversion (gslice) Source: https://github.com/bytedance/gg/blob/main/README.md Demonstrates converting slices to maps using various methods, including custom key-value mapping, boolean mapping, and grouping elements based on a key function. ```go ToMap([]int{1, 2, 3, 4, 5}, func(i int) (string, int) { return strconv.Itoa(i), i }) // {"1":1, "2":2, "3":3, "4":4, "5":5} ToBoolMap([]int{1, 2, 3, 3, 2}) // {1: true, 2: true, 3: true} ToMapValues([]int{1, 2, 3, 4, 5}, strconv.Itoa) // {"1":1, "2":2, "3":3, "4":4, "5":5} GroupBy([]int{1, 2, 3, 4, 5}, func(i int) string { if i%2 == 0 { return "even" } else { return "odd" } }) // {"even":[2,4], "odd":[1,3,5]} ``` -------------------------------- ### Go Pointer Utilities (gptr) Source: https://github.com/bytedance/gg/blob/main/README.md Provides utilities for working with pointers, including creating pointers from values, checking for nil pointers, and indirect access with default values. ```go import ( "github.com/bytedance/gg/gptr" ) ``` ```go a := gptr.Of(1) gptr.Indirect(a) // 1 b := gptr.OfNotZero(1) gptr.IsNotNil(b) // true gptr.IndirectOr(b, 2) // 1 gptr.Indirect(gptr.Map(b, strconv.Itoa)) // "1" c := gptr.OfNotZero(0) // nil gptr.IsNil(c) // true gptr.IndirectOr(c, 2) // 2 ``` -------------------------------- ### Generic Wrappers for Sync (gsync) Source: https://github.com/bytedance/gg/blob/main/_autodocs/README.md The gsync module provides generic wrappers around standard library sync primitives like sync.Map. ```Go import ( "github.com/bytedance/gg/gsync" ) // Example usage of Map[K, V] func ExampleGsyncMap() { var syncMap gsync.Map[string, int] syncMap.Store("a", 1) val, ok := syncMap.Load("a") if ok { // val is 1 } } ``` -------------------------------- ### Use Case: Callback Builders Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gfunc.md Shows how to build callback functions with pre-bound context using partial application. ```APIDOC ## Use Case: Callback Builders ### Description Construct callback functions with pre-bound context. ### Example ```go // Build callbacks with pre-bound context handleError := gfunc.Partial2(func(ctx, err string) { log.Printf("[%s] Error: %%s\n", ctx, err) }) handleAPIError := handleError.Partial("API") handleAPIError("connection failed") ``` ``` -------------------------------- ### Go Slice CURD Operations (gslice) Source: https://github.com/bytedance/gg/blob/main/README.md Illustrates CURD (Create, Update, Read, Delete) operations on slices, including checking for containment, indexing, finding elements, and accessing elements by index. ```go gslice.Contains([]int{1, 2, 3, 4, 5}, 2) // true gslice.ContainsAny([]int{1, 2, 3, 4, 5}, 2, 6) // true gslice.ContainsAll([]int{1, 2, 3, 4, 5}, 2, 6) // false gslice.Index([]int{1, 2, 3, 4, 5}, 3.Value()) // 2 gslice.Find([]int{1, 2, 3, 4, 5}, isEven).Value() // 2 gslice.First([]int{1, 2, 3, 4, 5}).Value() // 1 gslice.Get([]int{1, 2, 3, 4, 5}, 1).Value() // 2 gslice.Get([]int{1, 2, 3, 4, 5}, -1).Value() // Access element with negative index // 5 ``` -------------------------------- ### Example of ThenLazy in Gcond Switch Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/gcond.md Demonstrates using ThenLazy to provide a lazily evaluated string result for a When clause. The function is called only when the input matches the specified values. ```go gcond.Switch[string](1). When(1, 2).ThenLazy(func() string { return "One" }). Default("Other") // "One" ``` -------------------------------- ### New Source: https://github.com/bytedance/gg/blob/main/_autodocs/api-reference/collection-set.md Creates a new set containing the provided initial values. The set is implemented as a map for O(1) membership testing. ```APIDOC ## New ### Description Creates a new set containing the provided values. ### Signature ```go func New[T comparable](vs ...T) Set[T] ``` ### Parameters #### Variadic Parameters - **vs** (...T) - Required - Initial values for the set. ### Return Type - **Set[T]** - A new set initialized with the provided values. ### Example ```go import "github.com/bytedance/gg/collection/set" s := set.New(1, 2, 3) ``` ```