### ConcurrentMap Get Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/maputil.md Retrieves a value from the ConcurrentMap by key. Returns the zero value and false if the key does not exist. Demonstrates concurrent setting and getting of values. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/maputil" "sync" ) func main() { cm := maputil.NewConcurrentMap[string, int](100) var wg1 sync.WaitGroup wg1.Add(5) for i := 0; i < 5; i++ { go func(n int) { cm.Set(fmt.Sprintf("%d", n), n) wg1.Done() }(i) } wg1.Wait() var wg2 sync.WaitGroup wg2.Add(5) for j := 0; j < 5; j++ { go func(n int) { val, ok := cm.Get(fmt.Sprintf("%d", n)) fmt.Println(val, ok) wg2.Done() }(j) } wg2.Wait() // output: (order may change) // 1 true // 3 true // 2 true // 0 true // 4 true } ``` -------------------------------- ### Start a New Process Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/system.md Starts a new process with the given command and arguments. Returns the process ID and an error if the process fails to start. ```go import ( "fmt" "github.com/duke-git/lancet/v2/system" ) func main() { pid, err := system.StartProcess("sleep", "2") if err != nil { return } fmt.Println(pid) } ``` -------------------------------- ### ArrayQueue Size Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datastructure/queue.md Demonstrates how to get the number of elements in an ArrayQueue. Ensure the queue is initialized before calling Size. ```go package main import ( "fmt" queue "github.com/duke-git/lancet/v2/datastructure/queue" ) func main() { q := queue.NewArrayQueue[int](5) q.Enqueue(1) q.Enqueue(2) q.Enqueue(3) fmt.Println(q.Size()) // 3 } ``` -------------------------------- ### StartProcess Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/system.md Start a new process with the specified command and arguments. Returns the process ID and an error if the process fails to start. ```APIDOC ## StartProcess ### Description Start a new process with the specified name and arguments. ### Signature ```go func StartProcess(command string, args ...string) (int, error) ``` ### Example ```go import ( "fmt" "github.com/duke-git/lancet/v2/system" ) func main() { pid, err := system.StartProcess("sleep", "2") if err != nil { return } fmt.Println(pid) } ``` ``` -------------------------------- ### Get and Set OS Environment Variable Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/system.md Demonstrates getting and setting environment variables. Ensure the system package is imported. Note the output for nil error. ```go import ( "fmt" "github.com/duke-git/lancet/v2/system" ) func main() { err := system.SetOsEnv("foo", "abc") result := system.GetOsEnv("foo") fmt.Println(err) fmt.Println(result) // Output: // // abc } ``` -------------------------------- ### Get Today's Start Time Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datetime.md Returns the start of the current day in 'yyyy-mm-dd 00:00:00' format. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/datetime" ) func main() { startTime := datetime.GetTodayStartTime() fmt.Println(startTime) // Output: // 2023-06-29 00:00:00 } ``` -------------------------------- ### ConcurrentMap Has Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/maputil.md Checks if a ConcurrentMap contains a specific key. This example demonstrates concurrent setting of keys and then concurrently checking for their existence. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/maputil" "sync" ) func main() { cm := maputil.NewConcurrentMap[string, int](100) var wg1 sync.WaitGroup wg1.Add(5) for i := 0; i < 5; i++ { go func(n int) { cm.Set(fmt.Sprintf("%d", n), n) wg1.Done() }(i) } wg1.Wait() var wg2 sync.WaitGroup wg2.Add(5) for j := 0; j < 5; j++ { go func(n int) { ok := cm.Has(fmt.Sprintf("%d", n)) fmt.Println(ok) // true wg2.Done() }(j) } wg2.Wait() } ``` -------------------------------- ### StartProcess Source: https://github.com/duke-git/lancet/blob/main/README.md Starts a new process with the specified name and arguments. ```APIDOC ## StartProcess ### Description Starts a new process with the specified name and arguments. ### Method ```go func StartProcess(name string, args ...string) (*os.Process, error) ``` ### Parameters #### Path Parameters - **name** (string) - Required - The name of the process to start. - **args** ([]string) - Optional - Arguments for the process. ### Response - *os.Process: A pointer to the started process. - error: An error if the process fails to start. ``` -------------------------------- ### Install Lancet v2.x.x for Go 1.18+ Source: https://github.com/duke-git/lancet/blob/main/docs/en/guide/getting_started.md Use this command to install the latest version of Lancet v2.x.x, which is recommended for Go 1.18 and above due to its use of generics. ```bash go get github.com/duke-git/lancet/v2 // will install latest version of v2.x.x ``` -------------------------------- ### ConcurrentMap GetAndDelete Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/maputil.md Retrieves a value associated with a key and then deletes the key from the map. The example shows concurrent setting, then concurrent retrieval and deletion, verifying the deletion. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/maputil" "sync" ) func main() { cm := maputil.NewConcurrentMap[string, int](100) var wg1 sync.WaitGroup wg1.Add(5) for i := 0; i < 5; i++ { go func(n int) { cm.Set(fmt.Sprintf("%d", n), n) wg1.Done() }(i) } wg1.Wait() var wg2 sync.WaitGroup wg2.Add(5) for j := 0; j < 5; j++ { go func(n int) { val, ok := cm.GetAndDelete(fmt.Sprintf("%d", n)) fmt.Println(val, ok) //n, true _, ok = cm.Get(fmt.Sprintf("%d", n)) fmt.Println(val, ok) //false wg2.Done() }(j) } wg2.Wait() } ``` -------------------------------- ### Install Lancet v1.x.x for Go < 1.18 Source: https://github.com/duke-git/lancet/blob/main/docs/en/guide/getting_started.md Use this command to install the latest version of Lancet v1.x.x, suitable for Go versions below 1.18. ```bash go get github.com/duke-git/lancet // below go1.18, install latest version of v1.x.x ``` -------------------------------- ### ConcurrentMap GetOrSet Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/maputil.md Returns the existing value for a key if present; otherwise, it sets the key with the provided value and returns it. This example shows concurrent usage where each goroutine attempts to set and retrieve a value. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/maputil" "sync" ) func main() { cm := maputil.NewConcurrentMap[string, int](100) var wg sync.WaitGroup wg.Add(5) for i := 0; i < 5; i++ { go func(n int) { val, ok := cm.GetOrSet(fmt.Sprintf("%d", n), n) fmt.Println(val, ok) wg.Done() }(i) } wg.Wait() // output: (order may change) // 1 false // 3 false // 2 false // 0 false // 4 false } ``` -------------------------------- ### Or Function Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/condition.md Demonstrates the logical OR operation. It returns false only if both operands evaluate to false. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/condition" ) func main() { fmt.Println(condition.Or(0, "")) // false fmt.Println(condition.Or(0, 1)) // true fmt.Println(condition.Or(0, "0")) // true fmt.Println(condition.Or(1, "0")) // true } ``` -------------------------------- ### BeginOfMinute Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datetime.md Returns the start of the minute for a given time. ```APIDOC ## BeginOfMinute ### Description Returns the start of the minute for a given time. ### Function Signature ```go func BeginOfMinute(t time.Time) time.Time ``` ### Example ```go package main import ( "fmt" "time" "github.com/duke-git/lancet/v2/datetime" ) func main() { input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC) result := datetime.BeginOfMinute(input) fmt.Println(result) // Output: // 2023-01-08 18:50:00 +0000 UTC } ``` ``` -------------------------------- ### AES CTR Encrypt Example Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/cryptor.md Encrypts data using the AES CTR algorithm. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/cryptor" ) func main() { data := "hello" key := "abcdefghijklmnop" encrypted := cryptor.AesCtrEncrypt([]byte(data), []byte(key)) decrypted := cryptor.AesCtrDecrypt(encrypted, []byte(key)) fmt.Println(string(decrypted)) // Output: // hello } ``` -------------------------------- ### Get Beginning of Week - Go Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datetime.md Returns the start of the week for a given time, with an option to specify the starting day of the week. Imports 'time' and 'github.com/duke-git/lancet/v2/datetime'. ```go package main import ( "fmt" "time" "github.com/duke-git/lancet/v2/datetime" ) func main() { input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC) result := datetime.BeginOfWeek(input, time.Monday) fmt.Println(result) // Output: // 2023-01-09 00:00:00 +0000 UTC } ``` -------------------------------- ### Example: Reverse String Function Source: https://github.com/duke-git/lancet/blob/main/docs/en/guide/getting_started.md Demonstrates how to use the `Reverse` function from the `strutil` package to reverse a string. Ensure the `strutil` package is imported. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/strutil" ) func main() { s := "hello" rs := strutil.Reverse(s) fmt.Println(rs) //olleh } ``` -------------------------------- ### Remove OS Environment Variable Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/system.md Removes a single environment variable. Returns an error if the operation fails. This example shows setting, getting, removing, and getting again to demonstrate the effect. ```go import ( "fmt" "github.com/duke-git/lancet/v2/system" ) func main() { err1 := system.SetOsEnv("foo", "abc") result1 := GetOsEnv("foo") err2 := system.RemoveOsEnv("foo") result2 := GetOsEnv("foo") fmt.Println(err1) fmt.Println(err2) fmt.Println(result1) fmt.Println(result2) // Output: // // // abc // } ``` -------------------------------- ### Get Beginning of Week Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/datetime.md Use BeginOfWeek to get the time at the start of the week. You can specify the first day of the week (e.g., Sunday or Monday). Hours, minutes, seconds, and nanoseconds will be zeroed out. ```go package main import ( "fmt" "time" "github.com/duke-git/lancet/v2/datetime" ) func main() { input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC) result := datetime.BeginOfWeek(input, time.Monday) fmt.Println(result) // Output: // 2023-01-02 00:00:00 +0000 UTC } ``` -------------------------------- ### Get Beginning of Year - Go Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datetime.md Returns the start of the year for a given time. Imports 'time' and 'github.com/duke-git/lancet/v2/datetime'. ```go package main import ( "fmt" "time" "github.com/duke-git/lancet/v2/datetime" ) func main() { input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC) result := datetime.BeginOfYear(input) fmt.Println(result) // Output: // 2023-01-01 00:00:00 +0000 UTC } ``` -------------------------------- ### Create and Unbox Tuple7 - Go Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/tuple.md Demonstrates creating a Tuple7 with various data types and then unboxing its elements. Requires importing the tuple package. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/tuple" ) func main() { t := tuple.NewTuple7(1, 0.1, "a", true, 2, 2.2, "b") v1, v2, v3, v4, v5, v6, v7 := t.Unbox() fmt.Printf("%v %v %v %v %v %v %v", v1, v2, v3, v4, v5, v6, v7) // Output: 1 0.1 a true 2 2.2 b } ``` -------------------------------- ### Get Beginning of Month - Go Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datetime.md Returns the start of the month for a given time. Imports 'time' and 'github.com/duke-git/lancet/v2/datetime'. ```go package main import ( "fmt" "time" "github.com/duke-git/lancet/v2/datetime" ) func main() { input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC) result := datetime.BeginOfMonth(input) fmt.Println(result) // Output: // 2023-01-01 00:00:00 +0000 UTC } ``` -------------------------------- ### ShellSort Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/algorithm.md Shows how to apply ShellSort to sort a slice of integers using a provided comparator. The comparator needs to implement the constraints.Comparator interface. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/algorithm" ) type intComparator struct{} func (c *intComparator) Compare(v1 any, v2 any) int { val1, _ := v1.(int) val2, _ := v2.(int) //ascending order if val1 < val2 { return -1 } else if val1 > val2 { return 1 } return 0 } func main() { numbers := []int{2, 1, 5, 3, 6, 4} comparator := &intComparator{} algorithm.ShellSort(numbers, comparator) fmt.Println(numbers) // Output: // [1 2 3 4 5 6] } ``` -------------------------------- ### Get Beginning of Day - Go Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datetime.md Returns the start of the day for a given time. Imports 'time' and 'github.com/duke-git/lancet/v2/datetime'. ```go package main import ( "fmt" "time" "github.com/duke-git/lancet/v2/datetime" ) func main() { input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC) result := datetime.BeginOfDay(input) fmt.Println(result) // Output: // 2023-01-08 00:00:00 +0000 UTC } ``` -------------------------------- ### Create File Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/fileutil.md Use CreateFile to create a new file at the specified path. It returns true if creation is successful, false otherwise. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/fileutil" ) func main() { isCreatedSucceed := fileutil.CreateFile("./test.txt") fmt.Println(isCreatedSucceed) } ``` -------------------------------- ### Get Beginning of Hour - Go Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datetime.md Returns the start of the hour for a given time. Imports 'time' and 'github.com/duke-git/lancet/v2/datetime'. ```go package main import ( "fmt" "time" "github.com/duke-git/lancet/v2/datetime" ) func main() { input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC) result := datetime.BeginOfHour(input) fmt.Println(result) // Output: // 2023-01-08 18:00:00 +0000 UTC } ``` -------------------------------- ### Get Beginning of Minute - Go Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datetime.md Returns the start of the minute for a given time. Imports 'time' and 'github.com/duke-git/lancet/v2/datetime'. ```go package main import ( "fmt" "time" "github.com/duke-git/lancet/v2/datetime" ) func main() { input := time.Date(2023, 1, 8, 18, 50, 10, 100, time.UTC) result := datetime.BeginOfMinute(input) fmt.Println(result) // Output: // 2023-01-08 18:50:00 +0000 UTC } ``` -------------------------------- ### Create HttpClient with Configuration Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/netutil.md Instantiate an HttpClient with custom configurations like SSL enablement and handshake timeouts. This is useful for setting up specific network conditions for requests. ```go package main import ( "fmt" "net" "time" "github.com/duke-git/lancet/v2/netutil" ) func main() { httpClientCfg := netutil.HttpClientConfig{ SSLEnabled: true, HandshakeTimeout:10 * time.Second } httpClient := netutil.NewHttpClientWithConfig(&httpClientCfg) } ``` -------------------------------- ### Create New EventBus Instance Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/eventbus.md Instantiate a new EventBus for a specific data type. This example demonstrates creating an EventBus for integers, subscribing to an event, publishing to it, and verifying the received data. ```go import ( "fmt" "github.com/duke-git/lancet/v2/eventbus" ) func main() { eb := eventbus.NewEventBus[int]() receivedData := 0 listener := func(eventData int) { receivedData = eventData } eb.Subscribe("event1", listener, false, 0, nil) eb.Publish(eventbus.Event[int]{Topic: "event1", Payload: 1}) fmt.Println(receivedData) // Output: // 1 } ``` -------------------------------- ### Watcher Source: https://github.com/duke-git/lancet/blob/main/README.md Watcher is used for recording code execution time. It can start, stop, and reset the watch timer, and get the elapsed time of function execution. ```APIDOC ## Watcher ### Description Watcher is used for record code execution time. It can start/stop/reset the watch timer and get the elapsed time of function execution. ### Methods - **Start()**: Starts the watch timer. - **Stop()**: Stops the watch timer. - **Reset()**: Resets the watch timer. - **Elapsed()**: Returns the elapsed time in milliseconds. ``` -------------------------------- ### QuickSort Go Example Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/algorithm.md Sorts a slice using the Quick sort algorithm. Requires a custom comparator to define the sorting order. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/algorithm" ) type intComparator struct{} func (c *intComparator) Compare(v1 any, v2 any) int { val1, _ := v1.(int) val2, _ := v2.(int) //ascending order if val1 < val2 { return -1 } else if val1 > val2 { return 1 } return 0 } func main() { numbers := []int{2, 1, 5, 3, 6, 4} comparator := &intComparator{} algorithm.QuickSort(numbers, comparator) fmt.Println(numbers) // Output: // [1 2 3 4 5 6] } ``` -------------------------------- ### Extract Content Between Strings Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/strutil.md Use ExtractContent to get all substrings located between specified start and end markers within a larger string. It returns a slice of all found content. ```go import ( "fmt" "github.com/duke-git/lancet/v2/strutil" ) func main() { html := `content1aacontent2bbcontent1` result := strutil.ExtractContent(html, "", "") fmt.Println(result) // Output: // [content1 content2 content1] } ``` -------------------------------- ### List SubList Example Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/datastructure/list.md Extracts a portion of the list defined by a start index (inclusive) and an end index (exclusive). This returns a new list containing the specified elements. ```go package main import ( "fmt" list "github.com/duke-git/lancet/v2/datastructure/list" ) func main() { l := list.NewList([]int{1, 2, 3, 4, 5, 6}) fmt.Println(l.SubList(2, 5)) // [3 4 5] } ``` -------------------------------- ### Build URL with Query Parameters Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/netutil.md Use BuildUrl to construct a URL string from scheme, host, path, and a map of query parameters. Ensure all necessary parameters are provided. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/netutil" ) func main() { urlStr, err := netutil.BuildUrl( "https", "example.com", "query", map[string][]string{ "a": {"foo", "bar"}, "b": {"baz"}, }, ) fmt.Println(urlStr) fmt.Println(err) // Output: // https://example.com/query?a=foo&a=bar&b=baz // } ``` -------------------------------- ### Get stack trace information from XError Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/xerror.md The `StackTrace` method (aliased as `Stacks` in the example) returns stack trace information compatible with `pkg/errors`. This is useful for debugging and understanding error origins. ```go package main import ( "fmt" "strings" "github.com/duke-git/lancet/v2/xerror" ) func main() { err := xerror.New("error") stacks := err.Stacks() fmt.Println(stacks[0].Func) fmt.Println(stacks[0].Line) containFile := strings.Contains(stacks[0].File, "xxx.go") fmt.Println(containFile) } ``` -------------------------------- ### DayOfYear: Get Day Number of the Year Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/datetime.md Returns the day number of the year for a given date. For example, January 1st is day 0, and February 1st is day 31 in a non-leap year. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/datetime" "time" ) func main() { date1 := time.Date(2023, 02, 01, 1, 1, 1, 0, time.Local) result1 := datetime.DayOfYear(date1) date2 := time.Date(2023, 01, 02, 1, 1, 1, 0, time.Local) result2 := datetime.DayOfYear(date2) date3 := time.Date(2023, 01, 01, 1, 1, 1, 0, time.Local) result3 := datetime.DayOfYear(date3) fmt.Println(result1) fmt.Println(result2) fmt.Println(result3) // Output: // 31 // 1 // 0 } ``` -------------------------------- ### Create a New List Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/datastructure/list.md Initializes a new List with the provided slice data. Use this to create a list instance. ```go package main import ( "fmt" list "github.com/duke-git/lancet/v2/datastructure/list" ) func main() { li := list.NewList([]int{1, 2, 3}) fmt.Println(li) } ``` -------------------------------- ### BubbleSort Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/algorithm.md Demonstrates how to use BubbleSort with a custom comparator for integers. Ensure the comparator implements the constraints.Comparator interface. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/algorithm" ) type intComparator struct{} func (c *intComparator) Compare(v1 any, v2 any) int { val1, _ := v1.(int) val2, _ := v2.(int) //ascending order if val1 < val2 { return -1 } else if val1 > val2 { return 1 } return 0 } func main() { numbers := []int{2, 1, 5, 3, 6, 4} comparator := &intComparator{} algorithm.BubbleSort(numbers, comparator) fmt.Println(numbers) // Output: // [1 2 3 4 5 6] } ``` -------------------------------- ### ConcatBy Example with Custom Structs Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/slice.md Demonstrates how to use ConcatBy with a slice of custom structs, a struct separator, and a custom connector function. Requires importing the slice package. ```go import ( "fmt" "github.com/duke-git/lancet/v2/slice" ) func main() { type Person struct { Name string Age int } people := []Person{ {Name: "Alice", Age: 30}, {Name: "Bob", Age: 25}, {Name: "Charlie", Age: 35}, } sep := Person{Name: " | ", Age: 0} personConnector := func(a, b Person) Person { return Person{Name: a.Name + b.Name, Age: a.Age + b.Age} } result := slice.ConcatBy(people, sep, personConnector) fmt.Println(result.Name) fmt.Println(result.Age) // Output: // Alice | Bob | Charlie // 90 } ``` -------------------------------- ### Create a new Struct instance Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md Use the `New` function to create a `Struct` instance from any value. This is the entry point for using the structs package utilities. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/structs" ) func main() { type People struct { Name string `json:"name"` } p1 := &People{Name: "11"} s := structs.New(p1) fmt.Println(s.ToMap()) // Output: // map[name:11] } ``` -------------------------------- ### Get field kind Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md Use `Kind` to get the `reflect.Kind` of a struct field. This is useful for type checking and reflection-based logic. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/structs" ) func main() { type Parent struct { Name string Age int } p1 := &Parent{Age: 11} s := structs.New(p1) n, _ := s.Field("Name") a, _ := s.Field("Age") fmt.Println(n.Kind()) fmt.Println(a.Kind()) // Output: // string // int } ``` -------------------------------- ### Custom Backoff Strategy Example Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/retry.md Demonstrates how to implement and use a custom backoff strategy by defining a struct that satisfies the BackoffStrategy interface. ```go package main import ( "fmt" "errors" "log" "github.com/duke-git/lancet/v2/retry" ) type ExampleCustomBackoffStrategy struct { interval time.Duration } func (c *ExampleCustomBackoffStrategy) CalculateInterval() time.Duration { return c.interval + 1 } func main() { number := 0 increaseNumber := func() error { number++ if number == 3 { return nil } return errors.New("error occurs") } err := retry.Retry(increaseNumber, retry.RetryWithCustomBackoff(&ExampleCustomBackoffStrategy{interval: time.Microsecond * 50})) if err != nil { return } fmt.Println(number) // Output: // 3 } ``` -------------------------------- ### Send HTTP GET Request (Deprecated) Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/netutil.md Use HttpGet for sending HTTP GET requests. This function is deprecated and SendRequest is recommended. ```go package main import ( "fmt" "io/ioutil" "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { url := "https://jsonplaceholder.typicode.com/todos/1" header := map[string]string{ "Content-Type": "application/json", } resp, err := netutil.HttpGet(url, header) if err != nil { log.Fatal(err) } body, _ := ioutil.ReadAll(resp.Body) fmt.Println(body) } ``` -------------------------------- ### Using TryCatch for Error Handling Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/xerror.md Demonstrates how to use the TryCatch utility to simulate Java-style try-catch blocks. Use with caution as it deviates from Go's standard error handling. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/xerror" ) func main() { calledFinally := false calledCatch := false tc := xerror.NewTryCatch(context.Background()) tc.Try(func(ctx context.Context) error { return errors.New("error message ") }).Catch(func(ctx context.Context, err error) { calledCatch = true // Error in try block at /path/xxx.go:{line_number} - Cause: error message // fmt.Println(err.Error()) }).Finally(func(ctx context.Context) { calledFinally = true }).Do() fmt.Println(calledCatch) fmt.Println(calledFinally) // Output: // true // true } ``` -------------------------------- ### Create a New HashMap Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/datastructure/hashmap.md Instantiate a new HashMap with default capacity. Ensure the hashmap package is imported. ```go package main import ( "fmt" hashmap "github.com/duke-git/lancet/v2/datastructure/hashmap" ) func main() { hm := hashmap.NewHashMap() fmt.Println(hm) } ``` -------------------------------- ### ConcurrentMap Delete Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/maputil.md Deletes a key-value pair from the ConcurrentMap. This example demonstrates concurrent setting of values followed by concurrent deletion. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/maputil" "sync" ) func main() { cm := maputil.NewConcurrentMap[string, int](100) var wg1 sync.WaitGroup wg1.Add(5) for i := 0; i < 5; i++ { go func(n int) { cm.Set(fmt.Sprintf("%d", n), n) wg1.Done() }(i) } wg1.Wait() var wg2 sync.WaitGroup wg2.Add(5) for j := 0; j < 5; j++ { go func(n int) { cm.Delete(fmt.Sprintf("%d", n)) wg2.Done() }(i) } wg2.Wait() } ``` -------------------------------- ### Set Difference (Minus) Example Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/datastructure/set.md Demonstrates how to create a new set containing elements present in the origin set but not in the compared set. Requires importing the set package. ```go package main import ( "fmt" set "github.com/duke-git/lancet/v2/datastructure/set" ) func main() { set1 := set.New(1, 2, 3) set2 := set.New(2, 3, 4, 5) set3 := set.New(2, 3) res1 := set1.Minus(set2) fmt.Println(res1.Values()) //1 res2 := set2.Minus(set3) fmt.Println(res2.Values()) //4,5 } ``` -------------------------------- ### Get Total EventBus Listeners Count Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/eventbus.md Returns the total count of all listeners across all topics in the EventBus. Use this to get an overview of listener activity. ```go import ( "fmt" "github.com/duke-git/lancet/v2/eventbus" ) func main() { eb := eventbus.NewEventBus[int]() eb.Subscribe("event1", func(eventData int) {}, false, 0, nil) eb.Subscribe("event2", func(eventData int) {}, false, 0, nil) count := eb.GetAllListenersCount() fmt.Println(count) // Output: // 2 } ``` -------------------------------- ### Print Max Heap Structure in Go Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datastructure/heap.md Demonstrates how to print the tree structure of a max heap. Ensure the heap is initialized with a comparator. ```go package main import ( "fmt" heap "github.com/duke-git/lancet/v2/datastructure/heap" ) type intComparator struct{} func (c *intComparator) Compare(v1, v2 any) int { val1, _ := v1.(int) val2, _ := v2.(int) if val1 < val2 { return -1 } else if val1 > val2 { return 1 } return 0 } func main() { maxHeap := heap.NewMaxHeap[int](&intComparator{}) values := []int{6, 5, 2, 4, 7, 10, 12, 1, 3, 8, 9, 11} for _, v := range values { maxHeap.Push(v) } fmt.Println(maxHeap.PrintStructure()) // 12 // 9 11 // 4 8 10 7 // 1 3 5 6 2 } ``` -------------------------------- ### Equal Function Example Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/compare.md Demonstrates the usage of the Equal function to check for strict equality (both type and value) between different data types. Use this when you need to ensure both the type and the value match. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/compare" ) func main() { result1 := compare.Equal(1, 1) result2 := compare.Equal("1", "1") result3 := compare.Equal([]int{1, 2, 3}, []int{1, 2, 3}) result4 := compare.Equal(map[int]string{1: "a", 2: "b"}, map[int]string{1: "a", 2: "b"}) result5 := compare.Equal(1, "1") result6 := compare.Equal(1, int64(1)) result7 := compare.Equal([]int{1, 2}, []int{1, 2, 3}) fmt.Println(result1) fmt.Println(result2) fmt.Println(result3) fmt.Println(result4) fmt.Println(result5) fmt.Println(result6) fmt.Println(result7) // Output: // true // true // true // true // false // false // false } ``` -------------------------------- ### SM4 ECB Decrypt Example Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/cryptor.md Decrypts data using SM4 in ECB mode. Requires a 16-byte key. This example demonstrates a full encrypt-decrypt cycle. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/cryptor" ) func main() { key := []byte("1234567890abcdef") plaintext := []byte("hello world") encrypted := cryptor.Sm4EcbEncrypt(plaintext, key) decrypted := cryptor.Sm4EcbDecrypt(encrypted, key) fmt.Println(string(decrypted)) // Output: // hello world } ``` -------------------------------- ### Create a New Channel Instance Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/concurrency.md Use `NewChannel` to create a new instance of the `Channel` type. This is the starting point for using channel-based concurrency utilities. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/concurrency" ) func main() { c := concurrency.NewChannel[int]() } ``` -------------------------------- ### ParsePersonInfo Go Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/formatter.md Demonstrates extracting name and phone number, ID number, and tagged format from address strings using ParsePersonInfo. Requires importing the formatter package. ```go package main import ( "encoding/json" "fmt" "github.com/duke-git/lancet/v2/formatter" ) func main() { // 提取姓名和手机号 result1 := formatter.ParsePersonInfo("张三 13800138000 北京市朝阳区") fmt.Println("示例 1 - 姓名和手机号:") fmt.Printf("姓名: %s, 手机: %s, 地址: %s\n", result1.Name, result1.Mobile, result1.Addr) // 提取身份证号 result2 := formatter.ParsePersonInfo("李四 110101199001011234 上海市") fmt.Println("\n示例 2 - 身份证号:") fmt.Printf("姓名: %s, 身份证: %s, 地址: %s\n", result2.Name, result2.IDN, result2.Addr) // 带标签格式 result3 := formatter.ParsePersonInfo("收货人:王五 电话:13900139000 收货地址:天津市河西区友谊路20号") jsonData3, _ := json.MarshalIndent(result3, "", " ") fmt.Println("\n示例 3 - 带标签格式:") fmt.Println(string(jsonData3)) // Output: // 示例 1 - 姓名和手机号: // 姓名: 张三, 手机: 13800138000, 地址: 北京市朝阳区 // // 示例 2 - 身份证号: // 姓名: 李四, 身份证: 110101199001011234, 地址: 上海市 // // 示例 3 - 带标签格式: // { // "name": "王五", // "mobile": "13900139000", // "idn": "", // "postcode": "", // "province": "", // "city": "", // "region": "", // "street": "", // "addr": "天津市河西区友谊路20号" // } } ``` -------------------------------- ### DoublyLink: Create New Instance Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/datastructure/link.md Creates and returns a new instance of a DoublyLink. This is the entry point for using the DoublyLink data structure. ```go package main import ( "fmt" link "github.com/duke-git/lancet/v2/datastructure/link" ) func main() { lk := link.NewDoublyLink[int]() fmt.Println(lk) } ``` -------------------------------- ### Range Generate Number Slice Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/mathutil.md Creates a slice of numbers starting from 'start' with a specified 'count'. The step between elements is always 1. Handles both positive and negative counts, and works with integers and floats. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/mathutil" ) func main() { result1 := mathutil.Range(1, 4) result2 := mathutil.Range(1, -4) result3 := mathutil.Range(-4, 4) result4 := mathutil.Range(1.0, 4) fmt.Println(result1) fmt.Println(result2) fmt.Println(result3) fmt.Println(result4) // Output: // [1 2 3 4] // [1 2 3 4] // [-4 -3 -2 -1] // [1 2 3 4] } ``` -------------------------------- ### Get current date and time with format and timezone Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/datetime.md Retrieve the current date and time formatted according to the specified layout string. An optional timezone can be provided to get the time in a specific region. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/datetime" ) func main() { result1 := datetime.NowDateOrTime("yyyy-mm-dd hh:mm:ss") result2 := datetime.NowDateOrTime("yyyy-mm-dd hh:mm:ss", "EST") fmt.Println(result1) fmt.Println(result2) // Output: // 2023-07-26 15:01:30 // 2023-07-26 02:01:30 } ``` -------------------------------- ### Create a New SinglyLink Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/datastructure/link.md Instantiate a new, empty SinglyLink. This is the starting point for using the singly linked list. ```go package main import ( "fmt" link "github.com/duke-git/lancet/v2/datastructure/link" ) func main() { lk := link.NewSinglyLink[int]() fmt.Println(lk) } ``` -------------------------------- ### ArrayQueue IsFull Example Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datastructure/queue.md Demonstrates checking if an ArrayQueue is full. The queue is initially not full, but becomes full after enqueuing elements up to its capacity. ```go package main import ( "fmt" queue "github.com/duke-git/lancet/v2/datastructure/queue" ) func main() { q := queue.NewArrayQueue[int](3) fmt.Println(q.IsFull()) // false q.Enqueue(1) q.Enqueue(2) q.Enqueue(3) fmt.Println(q.IsFull()) // true } ``` -------------------------------- ### Generate RSA Key Pair Files Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/cryptor.md Creates RSA private and public key files in the current directory. Specify the key size and the desired filenames for the keys. ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/cryptor" ) func main() { err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem") if err != nil { fmt.Println(err) } } ``` -------------------------------- ### Send HTTP GET Request Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/netutil.md Use this function to send an HTTP GET request. It accepts a URL and optional parameters for headers, query parameters, and an HTTP client. This function is deprecated; use `SendRequest` instead. ```go package main import ( "fmt" "io/ioutil" "log" "github.com/duke-git/lancet/v2/netutil" ) func main() { url := "https://jsonplaceholder.typicode.com/todos/1" header := map[string]string{ "Content-Type": "application/json", } resp, err := netutil.HttpGet(url, header) if err != nil { log.Fatal(err) } body, _ := ioutil.ReadAll(resp.Body) fmt.Println(body) } ``` -------------------------------- ### Struct.TypeName() Source: https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md Get the name of the struct type. ```APIDOC ## Struct.TypeName() ### Description Return struct type name. ### Signature ```go func (s *Struct) TypeName() string ``` ### Example ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/structs" ) func main() { type Parent struct { Name string Age int } p := &Parent{Age: 11} s := structs.New(p) fmt.Println(s.TypeName()) // Output: // Parent } ``` ``` -------------------------------- ### Create a New Set Source: https://github.com/duke-git/lancet/blob/main/docs/api/packages/datastructure/set.md Initialize a new Set with optional initial elements. Duplicates provided during initialization are automatically handled. ```go package main import ( "fmt" set "github.com/duke-git/lancet/v2/datastructure/set" ) func main() { st := set.New[int](1,2,2,3) fmt.Println(st.Values()) //1,2,3 } ```