### Install strx Go Package Source: https://github.com/llyb120/yoya/blob/master/strx/README.md Instructions to install the `strx` package using Go's standard package management tool, `go get`. ```bash go get github.com/llyb120/yoya/strx ``` -------------------------------- ### Install Black Go Package Source: https://github.com/llyb120/yoya/blob/master/black/README.md Instructions to install the `black` Go package using the `go get` command, making it available for use in Go projects. ```bash go get github.com/llyb120/yoya/black ``` -------------------------------- ### Bash: Installing the Yoya supx Go Package Source: https://github.com/llyb120/yoya/blob/master/supx/README.md Provides the standard `go get` command to install the `github.com/llyb120/yoya/supx` package. This command fetches the module and its dependencies, making it available for import in Go projects. ```bash go get github.com/llyb120/yoya/supx ``` -------------------------------- ### Go cachex.NewBaseCache Initialization Example Source: https://github.com/llyb120/yoya/blob/master/cachex/README.md An example demonstrating how to initialize a new `cachex` base cache with specific expiration, default key expiration, and cleanup interval settings. ```Go cache := cachex.NewBaseCache[string, int](cachex.CacheOption{ Expire: 5 * time.Minute, // 5 minutes until cache destruction DefaultKeyExpire: 1 * time.Minute, // Keys default to 1 minute expiration CheckInterval: 30 * time.Second, // Check for expired keys every 30 seconds Destroy: func() { fmt.Println("Cache destroyed") } }) ``` -------------------------------- ### Example: Using supx.Record for Data Versioning and Undo/Redo Source: https://github.com/llyb120/yoya/blob/master/supx/README.md Illustrates the usage of `supx.Record` in Go for managing data versions. The example shows how to create a `Record`, commit states, modify data, and then rollback to previous states, demonstrating its utility for undo/redo functionality and history tracking. ```go package main import ( "fmt" "github.com/llyb120/yoya/supx" ) type Document struct { Title string Content string Version int } func main() { // Create Record doc := Document{ Title: "Initial Title", Content: "Initial content", Version: 1, } record := supx.NewRecord(doc) // Commit initial state record.Commit() // Modify data doc.Title = "Updated Title" doc.Version = 2 record.Set(doc) // Modify again doc.Content = "Updated content" doc.Version = 3 record.Set(doc) // Commit current state record.Commit() // View current data current := record.Get() fmt.Printf("Current: %+v\n", current) // Rollback to the previous commit point record.Rollback() rolledBack := record.Get() fmt.Printf("After rollback: %+v\n", rolledBack) // View history records history := record.History() fmt.Printf("History count: %d\n", len(history)) for i, h := range history { fmt.Printf("History[%d]: %+v\n", i, h) } } ``` -------------------------------- ### Install refx Go Library Source: https://github.com/llyb120/yoya/blob/master/refx/README.md Provides the command to install the `refx` Go library using the standard Go package manager. ```bash go get github.com/llyb120/yoya/refx ``` -------------------------------- ### Example: Using supx.Data for Dynamic Data Handling Source: https://github.com/llyb120/yoya/blob/master/supx/README.md Demonstrates how to use the `supx.Data` container in Go. This example covers creating a `Data` instance, setting main data and extra fields, retrieving data, and performing JSON serialization and deserialization, showcasing its dynamic and flexible data management capabilities. ```go package main import ( "fmt" "encoding/json" "github.com/llyb120/yoya/supx" ) type User struct { Name string `json:"name"` Age int `json:"age"` } func main() { // Create Data container data := supx.NewData[User]() // Set main data user := User{Name: "Alice", Age: 30} data.Set(user) // Set extra fields data.SetExtra("created_at", "2024-01-01") data.SetExtra("updated_at", "2024-01-02") data.SetExtra("version", 1) // Get data retrievedUser := data.Get() fmt.Printf("User: %+v\n", retrievedUser) // Get extra fields createdAt := data.GetExtra("created_at") fmt.Printf("Created at: %v\n", createdAt) // JSON serialization jsonData, err := json.Marshal(data) if err != nil { fmt.Printf("Marshal error: %v\n", err) return } fmt.Printf("JSON: %s\n", jsonData) // JSON deserialization var newData supx.Data[User] err = json.Unmarshal(jsonData, &newData) if err != nil { fmt.Printf("Unmarshal error: %v\n", err) return } fmt.Printf("Unmarshaled user: %+v\n", newData.Get()) fmt.Printf("Unmarshaled version: %v\n", newData.GetExtra("version")) } ``` -------------------------------- ### Complete Usage Example for Go Cachex Cache Library Source: https://github.com/llyb120/yoya/blob/master/cachex/README.md This Go code demonstrates the full functionality of the `cachex` library. It covers cache initialization with global and key-specific expiration, basic `Set` and `Get` operations, `SetExpire` for custom key lifetimes, `Gets` for batch retrieval, `GetOrSetFunc` for lazy loading with a function, and `Del` and `Clear` for cache invalidation. It also shows the `Destroy` callback for cache lifecycle management. ```go package main import ( "fmt" "time" "github.com/llyb120/yoya/cachex" ) type User struct { ID int Name string Age int } func main() { // 创建缓存 cache := cachex.NewBaseCache[string, User](cachex.CacheOption{ Expire: 10 * time.Minute, // 10分钟后销毁整个缓存 DefaultKeyExpire: 2 * time.Minute, // 键默认2分钟过期 CheckInterval: 1 * time.Minute, // 1分钟检查一次过期键 Destroy: func() { fmt.Println("Cache has been destroyed") }, }) defer cache.Destroy() // 基本操作 user1 := User{ID: 1, Name: "Alice", Age: 25} cache.Set("user:1", user1) // 设置自定义过期时间 user2 := User{ID: 2, Name: "Bob", Age: 30} cache.SetExpire("user:2", user2, 5*time.Minute) // 获取值 if value, found := cache.Get("user:1"); found { fmt.Printf("Found user: %+v\n", value) } // 批量获取 users := cache.Gets("user:1", "user:2", "user:3") fmt.Printf("Found %d users\n", len(users)) // 懒加载模式 user3 := cache.GetOrSetFunc("user:3", func() User { fmt.Println("Loading user 3 from database...") return User{ID: 3, Name: "Charlie", Age: 35} }) fmt.Printf("User 3: %+v\n", user3) // 再次获取,应该从缓存返回 user3Again := cache.GetOrSetFunc("user:3", func() User { fmt.Println("This should not be printed") return User{} }) fmt.Printf("User 3 (cached): %+v\n", user3Again) // 删除操作 cache.Del("user:1") // 验证删除 if _, found := cache.Get("user:1"); !found { fmt.Println("User 1 has been deleted") } // 清空缓存 cache.Clear() fmt.Println("Cache cleared") } ``` -------------------------------- ### Install YOYA Go Extension Toolkit Source: https://github.com/llyb120/yoya/blob/master/README.md Installs the YOYA Go language extension toolkit using the `go get` command. This command fetches the latest version of the library from its GitHub repository and adds it to your Go module cache. ```Bash go get github.com/llyb120/yoya ``` -------------------------------- ### Install yoya/stlx Go Library Source: https://github.com/llyb120/yoya/blob/master/stlx/README.md This snippet provides the command to install the `yoya/stlx` Go library using `go get`. This is the standard method for adding Go packages to your project. ```bash go get github.com/llyb120/yoya/stlx ``` -------------------------------- ### Go SkipList Usage Example Source: https://github.com/llyb120/yoya/blob/master/stlx/README.md Shows how to initialize a `SkipList`, insert integer values, perform range queries, and retrieve minimum and maximum elements. This example demonstrates the basic operations and ordered nature of the SkipList. ```Go sl := stlx.NewSkipList[int]() sl.Insert(10) sl.Insert(5) sl.Insert(15) sl.Insert(3) // 范围查询 values := sl.Range(5, 12) // [5, 10] // 最值查询 min, _ := sl.Min() max, _ := sl.Max() ``` -------------------------------- ### Go cachex.Cache Core Methods API Reference Source: https://github.com/llyb120/yoya/blob/master/cachex/README.md Comprehensive API documentation for the core methods of the `cachex` cache, including `Get`, `Gets`, `Set`, `SetExpire`, `Del`, `Clear`, `Destroy`, and `GetOrSetFunc`, detailing their functionality, parameters, return values, and usage examples. ```APIDOC Get(key K) (value V, ok bool) Function: Retrieves a value from the cache based on its key. Parameters: - key K: The key to look up. Returns: - V: The corresponding value. - bool: True if the value was found and not expired, false otherwise. Example: value, found := cache.Get("user:123") if found { fmt.Printf("Found: %v\n", value) } else { fmt.Println("Not found or expired") } --- Gets(keys ...K) []V Function: Retrieves values for multiple keys in a batch operation. Parameters: - keys ...K: A list of keys to look up. Returns: - []V: A list of found values (does not include values for keys not found). Example: values := cache.Gets("key1", "key2", "key3") fmt.Printf("Found %d values\n", len(values)) --- Set(key K, value V) Function: Sets a key-value pair in the cache using the default expiration time configured for the cache instance. Parameters: - key K: The key. - value V: The value. Example: cache.Set("user:123", "Alice") --- SetExpire(key K, value V, expire time.Duration) Function: Sets a key-value pair in the cache with a specific expiration time. Parameters: - key K: The key. - value V: The value. - expire time.Duration: The expiration duration for this specific key; 0 means never expire. Example: // Set to expire after 5 minutes cache.SetExpire("session:abc", sessionData, 5*time.Minute) // Set to never expire cache.SetExpire("config:db", dbConfig, 0) --- Del(key ...K) Function: Deletes one or more keys from the cache. Parameters: - key ...K: A list of keys to delete. Example: // Delete a single key cache.Del("user:123") // Delete multiple keys cache.Del("key1", "key2", "key3") --- Clear() Function: Clears all key-value pairs from the cache. Example: cache.Clear() --- Destroy() Function: Destroys the cache instance, stopping any background goroutines and executing the configured destroy callback. Example: cache.Destroy() --- GetOrSetFunc(key K, fn func() V) V Function: Retrieves the value for a key; if the key does not exist or is expired, it executes the provided function to generate the value, stores it, and then returns it. Parameters: - key K: The key. - fn func() V: A function that generates the value if it's not found in the cache. Returns: - V: The retrieved or newly generated value. Characteristics: - Thread-safe lazy loading pattern. - Helps prevent cache penetration issues. - Utilizes a double-checked locking pattern. Example: user := cache.GetOrSetFunc("user:123", func() User { // Load user information from the database return loadUserFromDB(123) }) ``` -------------------------------- ### Go refx.Call Example: Dynamic Method Invocation Source: https://github.com/llyb120/yoya/blob/master/refx/README.md Shows how to dynamically call methods on a Go object using `refx.Call`. This example covers methods with single and multiple return values, including error handling for method execution. ```go type Calculator struct{} func (c Calculator) Add(a, b int) int { return a + b } func (c Calculator) Divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } calc := Calculator{} // 调用简单方法 results, err := refx.Call(calc, "Add", 10, 20) if err == nil { sum := results[0].(int) fmt.Printf("10 + 20 = %d\n", sum) // 30 } // 调用返回多值的方法 results, err = refx.Call(calc, "Divide", 10.0, 3.0) if err == nil { quotient := results[0].(float64) callErr := results[1] fmt.Printf("10 / 3 = %f, error: %v\n", quotient, callErr) } ``` -------------------------------- ### Complete Usage Example of yoya/stlx Data Structures Source: https://github.com/llyb120/yoya/blob/master/stlx/README.md This Go program demonstrates the integration and basic usage of various data structures from the `yoya/stlx` library, including `OrderedMap`, `SkipList`, and `BiMap`, by calling dedicated example functions. It serves as an entry point to explore the library's capabilities. ```go package main import ( "fmt" "github.com/llyb120/yoya/stlx" ) func main() { // 1. OrderedMap 示例 fmt.Println("=== OrderedMap 示例 ===") orderedMapExample() // 2. SkipList 示例 fmt.Println("\n=== SkipList 示例 ===") skipListExample() // 3. BiMap 示例 fmt.Println("\n=== BiMap 示例 ===") biMapExample() // 4. 实际应用场景 fmt.Println("\n=== 实际应用场景 ===") realWorldExample() } ``` -------------------------------- ### Go strx Package Usage Example Source: https://github.com/llyb120/yoya/blob/master/strx/README.md Demonstrates how to use the `strx.Like` function for single and multi-pattern string matching, and how to utilize `strx.Number` for numeric string validation within a Go program. ```Go package main import ( "fmt" "github.com/llyb120/yoya/strx" ) func main() { fmt.Println(strx.Like("config.yaml", "*.yaml")) // true fmt.Println(strx.Like("12345", strx.Number)) // true // 多模式匹配:满足其一即可 ok := strx.Like("img.png", "*.jpg", "*.png") fmt.Println(ok) // true } ``` -------------------------------- ### Go: SmartWeakMap for Automatic Cache Management and Weak References Source: https://github.com/llyb120/yoya/blob/master/supx/README.md Demonstrates `supx.SmartWeakMap` for creating a Go cache with automatic memory management. It shows setting, getting, checking existence, and observing GC's effect on cache size, highlighting its weak reference behavior for keys. ```go package main import ( "fmt" "time" "github.com/llyb120/yoya/supx" ) type CacheKey struct { ID string } type CacheValue struct { Data string Timestamp time.Time } func main() { // 创建SmartWeakMap,最大容量100,过期时间5分钟 cache := supx.NewSmartWeakMap[*CacheKey, CacheValue](100, 5*time.Minute) // 设置数据 key1 := &CacheKey{ID: "user:123"} value1 := CacheValue{ Data: "User data for 123", Timestamp: time.Now(), } cache.Set(key1, value1) key2 := &CacheKey{ID: "user:456"} value2 := CacheValue{ Data: "User data for 456", Timestamp: time.Now(), } cache.Set(key2, value2) // 获取数据 if value, exists := cache.Get(key1); exists { fmt.Printf("Found: %+v\n", value) } // 检查存在性 fmt.Printf("Key1 exists: %v\n", cache.Has(key1)) fmt.Printf("Cache size: %d\n", cache.Size()) // 获取所有键 keys := cache.Keys() fmt.Printf("All keys: %v\n", len(keys)) // 当key1不再被引用时,会自动从缓存中清理 key1 = nil // 强制GC来演示自动清理 runtime.GC() time.Sleep(time.Millisecond * 100) fmt.Printf("Cache size after GC: %d\n", cache.Size()) } ``` -------------------------------- ### Complete Black Package Usage Example Source: https://github.com/llyb120/yoya/blob/master/black/README.md A comprehensive Go program demonstrating the full workflow of the `black` package, including serialization and deserialization of custom structs, slices, and maps, as well as the zero-copy `Byte2Str` function. It showcases error handling and typical usage patterns. ```go package main import ( "fmt" "github.com/llyb120/yoya/black" ) type Person struct { ID int64 Name string Age int } func main() { // 1. 结构体序列化与反序列化 original := &Person{ID: 100, Name: "Bob", Age: 25} // 序列化 data, err := black.ToBytes(original) if err != nil { panic(err) } // 反序列化 restored, err := black.FromBytes[Person](data) if err != nil { panic(err) } fmt.Printf("Original: %+v\n", original) fmt.Printf("Restored: %+v\n", restored) // 2. 切片操作 numbers := []int{10, 20, 30, 40, 50} numData, _ := black.ToBytes(numbers) restoredNums, _ := black.FromBytes[[]int](numData) fmt.Printf("Numbers: %v -> %v\n", numbers, restoredNums) // 3. 映射操作 scores := map[string]int{"Alice": 85, "Bob": 92, "Charlie": 78} scoreData, _ := black.ToBytes(scores) restoredScores, _ := black.FromBytes[map[string]int](scoreData) fmt.Printf("Scores: %v -> %v\n", scores, restoredScores) // 4. 零拷贝字符串转换 byteData := []byte("Hello, World!") str := black.Byte2Str(byteData) fmt.Printf("String: %s\n", str) } ``` -------------------------------- ### Go objx.Or Function for Zero-Value Handling Source: https://github.com/llyb120/yoya/blob/master/objx/README.md This Go example demonstrates the usage of the `objx.Or` function to provide default values for zero-initialized variables of various types, including strings, integers, and pointers. It shows how `objx.Or` can ensure a non-zero value is always returned, making code more robust against uninitialized data. ```Go package main import ( "fmt" "github.com/llyb120/yoya/objx" ) func main() { // String zero-value handling var name string displayName := objx.Or(name, "Anonymous") fmt.Printf("Display name: %s\n", displayName) name = "Alice" displayName = objx.Or(name, "Anonymous") fmt.Printf("Display name: %s\n", displayName) // Numeric zero-value handling var count int displayCount := objx.Or(count, 1) fmt.Printf("Display count: %d\n", displayCount) count = 5 displayCount = objx.Or(count, 1) fmt.Printf("Display count: %d\n", displayCount) // Pointer zero-value handling var ptr *string defaultStr := "default" result := objx.Or(ptr, &defaultStr) fmt.Printf("Result: %s\n", *result) actualStr := "actual" ptr = &actualStr result = objx.Or(ptr, &defaultStr) fmt.Printf("Result: %s\n", *result) } ``` -------------------------------- ### Basic Usage Example of YOYA Go Toolkit Source: https://github.com/llyb120/yoya/blob/master/README.md Demonstrates the fundamental usage of YOYA's `lsx`, `cachex`, and `objx` packages. It shows functional programming with `lsx.Map`, basic caching with `cachex.NewBaseCache`, and object manipulation like cloning and picking fields with `objx`. ```Go package main import ( "fmt" "time" "github.com/llyb120/yoya/lsx" "github.com/llyb120/yoya/cachex" "github.com/llyb120/yoya/objx" ) func main() { // 1. Use lsx for functional programming numbers := []int{1, 2, 3, 4, 5} doubled := lsx.Map(numbers, func(n, i int) int { return n * 2 }) fmt.Printf("Doubled: %v\n", doubled) // 2. Use cachex for caching cache := cachex.NewBaseCache[string, string](cachex.CacheOption{ DefaultKeyExpire: 5 * time.Minute, }) defer cache.Destroy() cache.Set("key1", "value1") if value, found := cache.Get("key1"); found { fmt.Printf("Cached: %s\n", value) } // 3. Use objx for object operations original := map[string]any{ "name": "Alice", "age": 30, "city": "Beijing", } clone, _ := objx.Clone(original) picked, _ := objx.Pick(original, "name", "age") fmt.Printf("Original: %v\n", original) fmt.Printf("Clone: %v\n", clone) fmt.Printf("Picked: %v\n", picked) } ``` -------------------------------- ### Serialize and Deserialize Go Maps with Black Source: https://github.com/llyb120/yoya/blob/master/black/README.md A Go example illustrating the process of serializing a string-to-integer map to a byte slice and then deserializing it back into a map using `black.ToBytes` and `black.FromBytes`. ```go mp := map[string]int{"a":1,"b":2} bs, _ := black.ToBytes(mp) clone, _ := black.FromBytes[map[string]int](bs) fmt.Println(clone) ``` -------------------------------- ### Go refx.GetFields Example: Introspecting Struct Fields Source: https://github.com/llyb120/yoya/blob/master/refx/README.md Provides an example of using `refx.GetFields` to obtain metadata and accessors (Getter/Setter functions) for all fields of a Go struct, including private ones, and demonstrates their usage for reading and modifying values. ```go type Person struct { Name string Age int Email string private bool } person := &Person{Name: "Alice", Age: 30, Email: "alice@example.com"} fields, err := refx.GetFields(person) if err != nil { log.Fatal(err) } for fieldName, fieldInfo := range fields { fmt.Printf("字段: %s, 类型: %s\n", fieldName, fieldInfo.Type) // 使用 Getter 获取值 value, err := fieldInfo.Getter() if err == nil { fmt.Printf(" 值: %v\n", value) } } // 使用 Setter 修改值 if nameField, ok := fields["Name"]; ok { err := nameField.Setter("Bob") if err == nil { fmt.Printf("名字已更改为: %s\n", person.Name) } } ``` -------------------------------- ### Go OrderedMap Usage Example Source: https://github.com/llyb120/yoya/blob/master/stlx/README.md Demonstrates how to initialize an `OrderedMap`, set key-value pairs, retrieve values by key or index, and iterate through elements while preserving insertion order. This example highlights the map's ability to maintain the order of elements as they are added. ```Go om := stlx.NewOrderedMap[string, int]() om.Set("first", 1) om.Set("second", 2) om.Set("third", 3) // 保持插入顺序 keys := om.Keys() // ["first", "second", "third"] // 按索引访问 value, ok := om.GetByIndex(1) // 2, true // 遍历保持顺序 for i := 0; i < om.Len(); i++ { value, _ := om.GetByIndex(i) fmt.Printf("Index %d: %v\n", i, value) } ``` -------------------------------- ### Go refx.GetMethods Example: Introspecting Object Methods Source: https://github.com/llyb120/yoya/blob/master/refx/README.md Demonstrates how to use `refx.GetMethods` to retrieve information about an object's methods, including their types and a `Caller` function for dynamic invocation. This example shows iterating through methods and calling a specific one. ```go type Service struct { name string } func (s Service) GetName() string { return s.name } func (s *Service) SetName(name string) { s.name = name } func (s Service) Process(data string, count int) (string, int) { return strings.Repeat(data, count), len(data) * count } service := &Service{name: "MyService"} methods, err := refx.GetMethods(service) if err != nil { log.Fatal(err) } for methodName, methodInfo := range methods { fmt.Printf("方法: %s, 类型: %s\n", methodName, methodInfo.Type) } // 使用 Caller 调用方法 if processMethod, ok := methods["Process"]; ok { results, err := processMethod.Caller("hello", 3) if err == nil { result := results[0].(string) length := results[1].(int) fmt.Printf("处理结果: %s, 长度: %d\n", result, length) } } ``` -------------------------------- ### Manage Asynchronous Operations and Goroutines with syncx Source: https://github.com/llyb120/yoya/blob/master/README.md Illustrates how to use the `syncx` package for asynchronous programming and goroutine management. It provides examples for asynchronously executing functions using `syncx.Async` and waiting for their results with `syncx.Await`. ```Go // Asynchronous execution asyncFunc := syncx.Async[int](expensiveComputation) result := asyncFunc(params) // Wait for result _ = syncx.Await(result, 5*time.Second) ``` -------------------------------- ### Perform Zero-Copy String Conversion and Object Serialization with black Source: https://github.com/llyb120/yoya/blob/master/README.md Illustrates how to use the `black` package for high-performance object and byte sequence conversion. It includes examples for zero-copy string conversion using `black.Byte2Str` and object serialization/deserialization with `black.ToBytes` and `black.FromBytes`. ```Go // Zero-copy string conversion str := black.Byte2Str([]byte("hello")) // Object serialization data, _ := black.ToBytes(&user) restored, _ := black.FromBytes[User](data) ``` -------------------------------- ### Serialize and Deserialize Go Slices with Black Source: https://github.com/llyb120/yoya/blob/master/black/README.md A concise Go example showing the serialization of an integer slice to bytes and its subsequent deserialization back into a slice using the `black` package's `ToBytes` and `FromBytes` functions. ```go nums := []int{1,2,3} bs, _ := black.ToBytes(nums) clone, _ := black.FromBytes[[]int](bs) fmt.Println(clone) // [1 2 3] ``` -------------------------------- ### Go refx: Real-World ORM and API Simulation Source: https://github.com/llyb120/yoya/blob/master/refx/README.md Provides practical examples of `refx` usage, simulating an ORM scenario for dynamic struct population from a map of data, and an API call scenario for dynamic method invocation (e.g., calling a validation method on a user object). This highlights `refx`'s utility in building flexible and dynamic applications. ```Go func realWorldExample() { // 模拟 ORM 场景:动态设置结构体字段 data := map[string]any{ "ID": 100, "Name": "Charlie", "Email": "charlie@example.com", } user := &User{} // 动态填充结构体 fields, _ := refx.GetFields(user) for key, value := range data { if field, ok := fields[key]; ok { err := field.Setter(value) if err != nil { fmt.Printf("设置字段 %s 失败: %v\n", key, err) } } } fmt.Printf("动态填充的用户: %+v\n", user) // 模拟 API 调用场景:动态方法调用 methods, _ := refx.GetMethods(user) // 调用验证方法 if validateMethod, ok := methods["Validate"]; ok { results, err := validateMethod.Caller() if err == nil { isValid := results[0].(bool) errors := results[1].([]string) if isValid { fmt.Println("用户数据验证通过") } else { fmt.Printf("用户数据验证失败: %v\n", errors) } } } } ``` -------------------------------- ### Go refx.Get Example: Accessing Public and Private Fields Source: https://github.com/llyb120/yoya/blob/master/refx/README.md Demonstrates how to use `refx.Get` to safely retrieve values from both public and private fields of a Go struct, including error handling for successful and failed access attempts. ```go type User struct { Name string age int // 私有字段 } user := User{Name: "Alice", age: 25} // 获取公有字段 name, err := refx.Get(user, "Name") if err == nil { fmt.Printf("Name: %v\n", name) // Alice } // 获取私有字段(使用 unsafe) age, err := refx.Get(user, "age") if err == nil { fmt.Printf("Age: %v\n", age) // 25 } ``` -------------------------------- ### Utilize Safe Reflection for Field Access and Dynamic Method Calls with refx Source: https://github.com/llyb120/yoya/blob/master/README.md Demonstrates the enhanced reflection capabilities provided by the `refx` package. It shows how to safely get and set field values on an object and how to dynamically call methods with arguments. ```Go // Safe field access value, _ := refx.Get(obj, "fieldName") _ = refx.Set(obj, "fieldName", newValue) // Dynamic method invocation results, _ := refx.Call(obj, "methodName", arg1, arg2) ``` -------------------------------- ### Go objx Package for Complex Data Manipulation Source: https://github.com/llyb120/yoya/blob/master/objx/README.md This comprehensive Go example showcases advanced features of the `objx` package for handling complex business objects like orders. It illustrates `DeepClone` for creating independent copies, `Pick` for extracting specific fields (with distinct options), `Or` for ensuring data integrity, and `Cast` for type conversion between different struct formats. This demonstrates how to effectively manage and transform complex data structures. ```Go package main import ( "fmt" "time" "github.com/llyb120/yoya/objx" ) type Order struct { ID string CustomerID string Items []OrderItem TotalAmount float64 Status string CreatedAt time.Time Metadata map[string]interface{} } type OrderItem struct { ProductID string Name string Price float64 Quantity int Category string } func main() { // Create order data orders := []Order{ { ID: "order-1", CustomerID: "customer-1", Items: []OrderItem{ {"prod-1", "Laptop", 999.99, 1, "Electronics"}, {"prod-2", "Mouse", 29.99, 2, "Electronics"}, }, TotalAmount: 1059.97, Status: "completed", CreatedAt: time.Now().AddDate(0, 0, -1), Metadata: map[string]interface{}{ "source": "web", "campaign": "summer_sale", }, }, { ID: "order-2", CustomerID: "customer-2", Items: []OrderItem{ {"prod-3", "Book", 19.99, 3, "Books"}, {"prod-4", "Pen", 2.99, 5, "Stationery"}, }, TotalAmount: 74.92, Status: "pending", CreatedAt: time.Now(), Metadata: map[string]interface{}{ "source": "mobile", "notes": "Gift wrap requested", }, }, } // 1. Clone order data for analysis ordersCopy, err := objx.DeepClone(orders) if err != nil { fmt.Printf("Clone error: %v\n", err) return } // 2. Extract all product names productNames := objx.Pick[string](orders, "Items.Name") fmt.Printf("All products: %v\n", productNames) // 3. Extract all categories (distinct) categories := objx.Pick[string](orders, "Items.Category", objx.Distinct) fmt.Printf("Categories: %v\n", categories) // 4. Extract all prices prices := objx.Pick[float64](orders, "Items.Price") fmt.Printf("All prices: %v\n", prices) // 5. Extract metadata sources sources := objx.Pick[string](orders, "Metadata.source") fmt.Printf("Order sources: %v\n", sources) // 6. Use Or to handle possible zero values for i, order := range ordersCopy { // Ensure status has a default value order.Status = objx.Or(order.Status, "unknown") // Ensure each item has a default category for j, item := range order.Items { order.Items[j].Category = objx.Or(item.Category, "Uncategorized") } ordersCopy[i] = order } fmt.Printf("Processed orders: %+v\n", ordersCopy) // 7. Type conversion example: Convert order to simplified format type SimpleOrder struct { ID string Total float64 Status string } var simpleOrders []SimpleOrder for _, order := range orders { var simple SimpleOrder err := objx.Cast(&simple, map[string]interface{}{ "ID": order.ID, "Total": order.TotalAmount, "Status": order.Status, }) if err == nil { simpleOrders = append(simpleOrders, simple) } } fmt.Printf("Simple orders: %+v\n", simpleOrders) } ``` -------------------------------- ### objx Go Package Characteristics and Usage Guidelines Source: https://github.com/llyb120/yoya/blob/master/objx/README.md This section outlines the key performance characteristics, important considerations, and applicable use cases for the `objx` Go package. It covers aspects like memory safety, handling of circular references, concurrency support, zero-copy optimizations, type optimizations, and specific caveats regarding private fields, function copying, and concurrency safety. ```APIDOC Performance Characteristics: - Memory Safety: Uses `unsafe` package for low-level operations but ensures memory safety. - Circular References: Efficient algorithm for detecting circular references. - Concurrency Support: `Pick` function supports concurrent execution of multiple rules. - Zero-Copy: Some operations avoid unnecessary memory copying. - Type Optimization: Specialized optimizations for different types. Important Considerations: 1. Private Fields: `DeepClone` can copy private fields, but use with caution. 2. Circular References: Automatically handles circular references, but may impact performance. 3. Function Copying: Function types cannot be deep copied; they return the original value directly. 4. Concurrency Safety: Except for the `Pick` function, other functions do not guarantee concurrency safety. 5. Memory Usage: Deep copying creates full object replicas; pay attention to memory usage. Applicable Scenarios: - Object Cloning: Scenarios requiring complete replication of complex object structures. - Data Extraction: Extracting specific fields from complex nested structures. - Configuration Handling: Processing complex configuration objects and data transformations. - API Data: Handling complex JSON data structures from APIs. - Testing Scenarios: Creating independent copies of test data. ``` -------------------------------- ### Real-World Application of stlx Data Structures in Go Source: https://github.com/llyb120/yoya/blob/master/stlx/README.md This comprehensive example simulates a simple task scheduling system to showcase the combined utility of `stlx.SkipList` (for task prioritization), `stlx.MultiMap` (for managing user tasks), and `stlx.OrderedMap` (for task execution history). It demonstrates how these structures can work together to manage complex data flows in a practical application. ```go func realWorldExample() { // 模拟一个简单的任务调度系统 // 使用 SkipList 管理任务优先级 taskQueue := stlx.NewSkipList[Task]() // 使用 MultiMap 管理用户的多个任务 userTasks := stlx.NewMultiMap[string, int]() // 使用 OrderedMap 记录任务执行历史 taskHistory := stlx.NewOrderedMap[int, string]() // 添加任务 tasks := []Task{ {ID: 1, Priority: 5, Name: "发送邮件"}, {ID: 2, Priority: 1, Name: "备份数据"}, {ID: 3, Priority: 8, Name: "处理订单"}, {ID: 4, Priority: 3, Name: "生成报告"}, } for _, task := range tasks { taskQueue.Insert(task) userTasks.Set("admin", task.ID) taskHistory.Set(task.ID, fmt.Sprintf("任务创建: %s", task.Name)) } // 按优先级处理任务 fmt.Println("按优先级处理任务:") min, ok := taskQueue.Min() for ok { fmt.Printf(" 执行任务: %s (优先级: %d)\n", min.Name, min.Priority) taskQueue.Remove(min) // 更新历史 taskHistory.Set(min.ID, fmt.Sprintf("任务完成: %s", min.Name)) min, ok = taskQueue.Min() } // 查看用户的所有任务 adminTasks := userTasks.Get("admin") fmt.Printf("\n管理员的任务ID: %v\n", adminTasks) // 查看任务历史(按时间顺序) fmt.Println("\n任务历史记录:") for i := 0; i < taskHistory.Len(); i++ { taskID := taskHistory.Keys()[i] history, _ := taskHistory.Get(taskID) fmt.Printf(" 任务%d: %s\n", taskID, history) } } type Task struct { ID int Priority int Name string } // 实现比较接口,用于 SkipList 排序 func (t Task) Less(other Task) bool { return t.Priority < other.Priority } ``` -------------------------------- ### Define User Struct and Methods for Reflection Examples Source: https://github.com/llyb120/yoya/blob/master/refx/README.md Defines a `User` struct with public (`ID`, `Name`, `Email`) and private (`password`) fields, along with methods (`GetDisplayName`, `SetPassword`, `Validate`). This struct serves as the primary target for demonstrating dynamic reflection operations using the `refx` library. ```Go type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` password string // 私有字段 } func (u User) GetDisplayName() string { return fmt.Sprintf("%s <%s>", u.Name, u.Email) } func (u *User) SetPassword(password string) error { if len(password) < 6 { return fmt.Errorf("密码长度不能少于6位") } u.password = password return nil } func (u User) Validate() (bool, []string) { var errors []string if u.Name == "" { errors = append(errors, "姓名不能为空") } if u.Email == "" { errors = append(errors, "邮箱不能为空") } return len(errors) == 0, errors } ``` -------------------------------- ### Using OrderedMap in Go for Configuration Management Source: https://github.com/llyb120/yoya/blob/master/stlx/README.md This example demonstrates how to use `stlx.OrderedMap` to store and retrieve configuration items while preserving their insertion order. It shows setting values, iterating through keys in order, and accessing elements by index, useful for scenarios like configuration files or attribute lists. ```go func orderedMapExample() { // 创建有序映射 config := stlx.NewOrderedMap[string, interface{}]() // 按顺序添加配置项 config.Set("database.host", "localhost") config.Set("database.port", 5432) config.Set("database.name", "myapp") config.Set("server.port", 8080) config.Set("server.debug", true) // 保持插入顺序输出 fmt.Println("配置项(按插入顺序):") for i := 0; i < config.Len(); i++ { key := config.Keys()[i] value, _ := config.Get(key) fmt.Printf(" %s: %v\n", key, value) } // 按索引访问 firstValue, _ := config.GetByIndex(0) fmt.Printf("第一个配置项的值: %v\n", firstValue) } ```