diff --git a/container/gmap/gmap_hash_any_any_map.go b/container/gmap/gmap_hash_any_any_map.go index a1f4b3230b4..9b268ae0d65 100644 --- a/container/gmap/gmap_hash_any_any_map.go +++ b/container/gmap/gmap_hash_any_any_map.go @@ -266,7 +266,7 @@ func (m *AnyAnyMap) GetVar(key interface{}) *gvar.Var { return gvar.New(m.Get(key)) } -// GetVarOrSet returns a Var with result from GetVarOrSet. +// GetVarOrSet returns a Var with result from GetOrSet. // The returned Var is un-concurrent safe. func (m *AnyAnyMap) GetVarOrSet(key interface{}, value interface{}) *gvar.Var { return gvar.New(m.GetOrSet(key, value)) diff --git a/container/gmap/gmap_z_example_any_any_test.go b/container/gmap/gmap_z_example_any_any_test.go index d320db84b36..6908978b777 100644 --- a/container/gmap/gmap_z_example_any_any_test.go +++ b/container/gmap/gmap_z_example_any_any_test.go @@ -8,72 +8,413 @@ package gmap_test import ( "fmt" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/container/gmap" "github.com/gogf/gf/v2/frame/g" ) -func ExampleNew() { +func ExampleAnyAnyMap_Iterator() { + m := gmap.New() + for i := 0; i < 10; i++ { + m.Set(i, i*2) + } + + var totalKey, totalValue int + m.Iterator(func(k interface{}, v interface{}) bool { + totalKey += k.(int) + totalValue += v.(int) + + return totalKey < 10 + }) + + fmt.Println("totalKey:", totalKey) + fmt.Println("totalValue:", totalValue) + + // May Output: + // totalKey: 11 + // totalValue: 22 +} + +func ExampleAnyAnyMap_Clone() { m := gmap.New() - // Add data. m.Set("key1", "val1") + fmt.Println(m) - // Print size. - fmt.Println(m.Size()) + n := m.Clone() + fmt.Println(n) + + // Output: + // {"key1":"val1"} + // {"key1":"val1"} +} + +func ExampleAnyAnyMap_Map() { + // non concurrent-safety, a pointer to the underlying data + m1 := gmap.New() + m1.Set("key1", "val1") + fmt.Println("m1:", m1) + + n1 := m1.Map() + fmt.Println("before n1:", n1) + m1.Set("key1", "val2") + fmt.Println("after n1:", n1) + + // concurrent-safety, copy of underlying data + m2 := gmap.New(true) + m2.Set("key1", "val1") + fmt.Println("m2:", m2) + + n2 := m2.Map() + fmt.Println("before n2:", n2) + m2.Set("key1", "val2") + fmt.Println("after n2:", n2) + + // Output: + // m1: {"key1":"val1"} + // before n1: map[key1:val1] + // after n1: map[key1:val2] + // m2: {"key1":"val1"} + // before n2: map[key1:val1] + // after n2: map[key1:val1] +} + +func ExampleAnyAnyMap_MapCopy() { + m := gmap.New() + + m.Set("key1", "val1") + m.Set("key2", "val2") + fmt.Println(m) + + n := m.MapCopy() + fmt.Println(n) + + // Output: + // {"key1":"val1","key2":"val2"} + // map[key1:val1 key2:val2] +} + +func ExampleAnyAnyMap_MapStrAny() { + m := gmap.New() + m.Set(1001, "val1") + m.Set(1002, "val2") + + n := m.MapStrAny() + fmt.Printf("%#v", n) + + // Output: + // map[string]interface {}{"1001":"val1", "1002":"val2"} +} + +func ExampleAnyAnyMap_FilterEmpty() { + m := gmap.NewFrom(g.MapAnyAny{ + "k1": "", + "k2": nil, + "k3": 0, + "k4": 1, + }) + m.FilterEmpty() + fmt.Println(m.Map()) + + // Output: + // map[k4:1] +} + +func ExampleAnyAnyMap_FilterNil() { + m := gmap.NewFrom(g.MapAnyAny{ + "k1": "", + "k2": nil, + "k3": 0, + "k4": 1, + }) + m.FilterNil() + fmt.Printf("%#v", m.Map()) + + // Output: + // map[interface {}]interface {}{"k1":"", "k3":0, "k4":1} +} + +func ExampleAnyAnyMap_Set() { + m := gmap.New() + + m.Set("key1", "val1") + fmt.Println(m) + + // Output: + // {"key1":"val1"} +} + +func ExampleAnyAnyMap_Sets() { + m := gmap.New() addMap := make(map[interface{}]interface{}) + addMap["key1"] = "val1" addMap["key2"] = "val2" addMap["key3"] = "val3" - addMap[1] = 1 - - fmt.Println(m.Values()) - // Batch add data. m.Sets(addMap) + fmt.Println(m) - // Gets the value of the corresponding key. - fmt.Println(m.Get("key3")) + // Output: + // {"key1":"val1","key2":"val2","key3":"val3"} +} - // Get the value by key, or set it with given key-value if not exist. - fmt.Println(m.GetOrSet("key4", "val4")) +func ExampleAnyAnyMap_Search() { + m := gmap.New() - // Set key-value if the key does not exist, then return true; or else return false. - fmt.Println(m.SetIfNotExist("key3", "val3")) + m.Set("key1", "val1") - // Remove key - m.Remove("key2") - fmt.Println(m.Keys()) + value, found := m.Search("key1") + if found { + fmt.Println("find key1 value:", value) + } - // Batch remove keys. - m.Removes([]interface{}{"key1", 1}) - fmt.Println(m.Keys()) + value, found = m.Search("key2") + if !found { + fmt.Println("key2 not find") + } - // Contains checks whether a key exists. - fmt.Println(m.Contains("key3")) + // Output: + // find key1 value: val1 + // key2 not find +} - // Flip exchanges key-value of the map, it will change key-value to value-key. - m.Flip() - fmt.Println(m.Map()) +func ExampleAnyAnyMap_Get() { + m := gmap.New() - // Clear deletes all data of the map. - m.Clear() + m.Set("key1", "val1") - fmt.Println(m.Size()) + fmt.Println("key1 value:", m.Get("key1")) + fmt.Println("key2 value:", m.Get("key2")) + + // Output: + // key1 value: val1 + // key2 value: +} + +func ExampleAnyAnyMap_Pop() { + var m gmap.Map + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Pop()) + + // May Output: + // k1 v1 +} + +func ExampleAnyAnyMap_Pops() { + var m gmap.Map + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Pops(-1)) + fmt.Println("size:", m.Size()) + + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Pops(2)) + fmt.Println("size:", m.Size()) // May Output: - // 1 - // [val1] - // val3 - // val4 + // map[k1:v1 k2:v2 k3:v3 k4:v4] + // size: 0 + // map[k1:v1 k2:v2] + // size: 2 +} + +func ExampleAnyAnyMap_GetOrSet() { + m := gmap.New() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSet("key1", "NotExistValue")) + fmt.Println(m.GetOrSet("key2", "val2")) + + // Output: + // val1 + // val2 +} + +func ExampleAnyAnyMap_GetOrSetFunc() { + m := gmap.New() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSetFunc("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFunc("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleAnyAnyMap_GetOrSetFuncLock() { + m := gmap.New() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSetFuncLock("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFuncLock("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleAnyAnyMap_GetVar() { + m := gmap.New() + m.Set("key1", "val1") + + fmt.Println(m.GetVar("key1")) + fmt.Println(m.GetVar("key2").IsNil()) + + // Output: + // val1 + // true +} + +func ExampleAnyAnyMap_GetVarOrSet() { + m := gmap.New() + m.Set("key1", "val1") + + fmt.Println(m.GetVarOrSet("key1", "NotExistValue")) + fmt.Println(m.GetVarOrSet("key2", "val2")) + + // Output: + // val1 + // val2 +} + +func ExampleAnyAnyMap_GetVarOrSetFunc() { + m := gmap.New() + m.Set("key1", "val1") + + fmt.Println(m.GetVarOrSetFunc("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetVarOrSetFunc("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleAnyAnyMap_GetVarOrSetFuncLock() { + m := gmap.New() + m.Set("key1", "val1") + + fmt.Println(m.GetVarOrSetFuncLock("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetVarOrSetFuncLock("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleAnyAnyMap_SetIfNotExist() { + var m gmap.Map + fmt.Println(m.SetIfNotExist("k1", "v1")) + fmt.Println(m.SetIfNotExist("k1", "v2")) + fmt.Println(m.Map()) + + // Output: + // true // false - // [key4 key1 key3 1] - // [key4 key3] + // map[k1:v1] +} + +func ExampleAnyAnyMap_SetIfNotExistFunc() { + var m gmap.Map + fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + return "v1" + })) + fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: // true - // map[val3:key3 val4:key4] + // false + // map[k1:v1] +} + +func ExampleAnyAnyMap_SetIfNotExistFuncLock() { + var m gmap.Map + fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + return "v1" + })) + fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleAnyAnyMap_Remove() { + var m gmap.Map + m.Set("k1", "v1") + + fmt.Println(m.Remove("k1")) + fmt.Println(m.Remove("k2")) + fmt.Println(m.Size()) + + // Output: + // v1 + // // 0 } +func ExampleAnyAnyMap_Removes() { + var m gmap.Map + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + removeList := make([]interface{}, 2) + removeList = append(removeList, "k1") + removeList = append(removeList, "k2") + + m.Removes(removeList) + + fmt.Println(m.Map()) + + // Output: + // map[k3:v3 k4:v4] +} + func ExampleAnyAnyMap_Keys() { var m gmap.Map m.Sets(g.MapAnyAny{ @@ -83,11 +424,9 @@ func ExampleAnyAnyMap_Keys() { "k4": "v4", }) fmt.Println(m.Keys()) - fmt.Println(m.Values()) // May Output: // [k1 k2 k3 k4] - // [v2 v3 v4 v1] } func ExampleAnyAnyMap_Values() { @@ -98,28 +437,30 @@ func ExampleAnyAnyMap_Values() { "k3": "v3", "k4": "v4", }) - fmt.Println(m.Keys()) fmt.Println(m.Values()) // May Output: - // [k1 k2 k3 k4] - // [v2 v3 v4 v1] + // [v1 v2 v3 v4] } -func ExampleAnyAnyMap_Flip() { +func ExampleAnyAnyMap_Contains() { var m gmap.Map m.Sets(g.MapAnyAny{ "k1": "v1", "k2": "v2", + "k3": "v3", + "k4": "v4", }) - m.Flip() - fmt.Println(m.Map()) - // May Output: - // map[v1:k1 v2:k2] + fmt.Println(m.Contains("k1")) + fmt.Println(m.Contains("k5")) + + // Output: + // true + // false } -func ExampleAnyAnyMap_Pop() { +func ExampleAnyAnyMap_Size() { var m gmap.Map m.Sets(g.MapAnyAny{ "k1": "v1", @@ -127,17 +468,26 @@ func ExampleAnyAnyMap_Pop() { "k3": "v3", "k4": "v4", }) - fmt.Println(m.Pop()) - fmt.Println(m.Pops(2)) + fmt.Println(m.Size()) - // May Output: - // k1 v1 - // map[k2:v2 k4:v4] - // 1 + // Output: + // 4 } -func ExampleAnyAnyMap_Pops() { +func ExampleAnyAnyMap_IsEmpty() { + var m gmap.Map + fmt.Println(m.IsEmpty()) + + m.Set("k1", "v1") + fmt.Println(m.IsEmpty()) + + // Output: + // true + // false +} + +func ExampleAnyAnyMap_Clear() { var m gmap.Map m.Sets(g.MapAnyAny{ "k1": "v1", @@ -145,54 +495,92 @@ func ExampleAnyAnyMap_Pops() { "k3": "v3", "k4": "v4", }) - fmt.Println(m.Pop()) - fmt.Println(m.Pops(2)) - fmt.Println(m.Size()) - // May Output: - // k1 v1 - // map[k2:v2 k4:v4] - // 1 + m.Clear() + + fmt.Println(m.Map()) + + // Output: + // map[] } -func ExampleAnyAnyMap_FilterEmpty() { - m := gmap.NewFrom(g.MapAnyAny{ - "k1": "", - "k2": nil, - "k3": 0, - "k4": 1, +func ExampleAnyAnyMap_Replace() { + var m gmap.Map + m.Sets(g.MapAnyAny{ + "k1": "v1", }) - m.FilterEmpty() + + var n gmap.Map + n.Sets(g.MapAnyAny{ + "k2": "v2", + }) + fmt.Println(m.Map()) - // May Output: - // map[k4:1] + m.Replace(n.Map()) + fmt.Println(m.Map()) + + n.Set("k2", "v1") + fmt.Println(m.Map()) + + // Output: + // map[k1:v1] + // map[k2:v2] + // map[k2:v1] } -func ExampleAnyAnyMap_FilterNil() { - m := gmap.NewFrom(g.MapAnyAny{ - "k1": "", - "k2": nil, - "k3": 0, - "k4": 1, +func ExampleAnyAnyMap_LockFunc() { + var m gmap.Map + m.Sets(g.MapAnyAny{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, }) - m.FilterNil() - fmt.Println(m.Map()) - // May Output: - // map[k1: k3:0 k4:1] + m.LockFunc(func(m map[interface{}]interface{}) { + totalValue := 0 + for _, v := range m { + totalValue += v.(int) + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 } -func ExampleAnyAnyMap_SetIfNotExist() { +func ExampleAnyAnyMap_RLockFunc() { var m gmap.Map - fmt.Println(m.SetIfNotExist("k1", "v1")) - fmt.Println(m.SetIfNotExist("k1", "v1")) + m.Sets(g.MapAnyAny{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + m.RLockFunc(func(m map[interface{}]interface{}) { + totalValue := 0 + for _, v := range m { + totalValue += v.(int) + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 +} + +func ExampleAnyAnyMap_Flip() { + var m gmap.Map + m.Sets(g.MapAnyAny{ + "k1": "v1", + }) + m.Flip() fmt.Println(m.Map()) // Output: - // true - // false - // map[k1:v1] + // map[v1:k1] } func ExampleAnyAnyMap_Merge() { @@ -205,3 +593,78 @@ func ExampleAnyAnyMap_Merge() { // May Output: // map[key1:val1 key2:val2] } + +func ExampleAnyAnyMap_String() { + var m gmap.Map + m.Sets(g.MapAnyAny{ + "k1": "v1", + }) + + fmt.Println(m.String()) + + // Output: + // {"k1":"v1"} +} + +func ExampleAnyAnyMap_MarshalJSON() { + var m gmap.Map + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + bytes, err := json.Marshal(&m) + if err == nil { + fmt.Println(gconv.String(bytes)) + } + + // Output: + // {"k1":"v1","k2":"v2","k3":"v3","k4":"v4"} +} + +func ExampleAnyAnyMap_UnmarshalJSON() { + var m gmap.Map + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + var n gmap.Map + + err := json.Unmarshal(gconv.Bytes(m.String()), &n) + if err == nil { + fmt.Println(n.Map()) + } + + // Output: + // map[k1:v1 k2:v2 k3:v3 k4:v4] +} + +func ExampleAnyAnyMap_UnmarshalValue() { + type User struct { + Uid int + Name string + Pass1 string `gconv:"password1"` + Pass2 string `gconv:"password2"` + } + + var ( + m gmap.AnyAnyMap + user = User{ + Uid: 1, + Name: "john", + Pass1: "123", + Pass2: "456", + } + ) + if err := gconv.Scan(user, &m); err == nil { + fmt.Printf("%#v", m.Map()) + } + + // Output: + // map[interface {}]interface {}{"Name":"john", "Uid":1, "password1":"123", "password2":"456"} +} diff --git a/container/gmap/gmap_z_example_int_any_test.go b/container/gmap/gmap_z_example_int_any_test.go new file mode 100644 index 00000000000..a89b2d1db94 --- /dev/null +++ b/container/gmap/gmap_z_example_int_any_test.go @@ -0,0 +1,661 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with gm file, +// You can obtain one at https://github.com/gogf/gf. + +package gmap_test + +import ( + "fmt" + "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/util/gconv" +) + +func ExampleIntAnyMap_Iterator() { + m := gmap.NewIntAnyMap() + for i := 0; i < 10; i++ { + m.Set(i, i*2) + } + + var totalKey, totalValue int + m.Iterator(func(k int, v interface{}) bool { + totalKey += k + totalValue += v.(int) + + return totalKey < 10 + }) + + fmt.Println("totalKey:", totalKey) + fmt.Println("totalValue:", totalValue) + + // May Output: + // totalKey: 11 + // totalValue: 22 +} + +func ExampleIntAnyMap_Clone() { + m := gmap.NewIntAnyMap() + + m.Set(1, "val1") + fmt.Println(m) + + n := m.Clone() + fmt.Println(n) + + // Output: + // {"1":"val1"} + // {"1":"val1"} +} + +func ExampleIntAnyMap_Map() { + // non concurrent-safety, a pointer to the underlying data + m1 := gmap.NewIntAnyMap() + m1.Set(1, "val1") + fmt.Println("m1:", m1) + + n1 := m1.Map() + fmt.Println("before n1:", n1) + m1.Set(1, "val2") + fmt.Println("after n1:", n1) + + // concurrent-safety, copy of underlying data + m2 := gmap.New(true) + m2.Set(1, "val1") + fmt.Println("m2:", m2) + + n2 := m2.Map() + fmt.Println("before n2:", n2) + m2.Set(1, "val2") + fmt.Println("after n2:", n2) + + // Output: + // m1: {"1":"val1"} + // before n1: map[1:val1] + // after n1: map[1:val2] + // m2: {"1":"val1"} + // before n2: map[1:val1] + // after n2: map[1:val1] +} + +func ExampleIntAnyMap_MapCopy() { + m := gmap.NewIntAnyMap() + + m.Set(1, "val1") + m.Set(2, "val2") + fmt.Println(m) + + n := m.MapCopy() + fmt.Println(n) + + // Output: + // {"1":"val1","2":"val2"} + // map[1:val1 2:val2] +} + +func ExampleIntAnyMap_MapStrAny() { + m := gmap.NewIntAnyMap() + m.Set(1001, "val1") + m.Set(1002, "val2") + + n := m.MapStrAny() + fmt.Printf("%#v", n) + + // Output: + // map[string]interface {}{"1001":"val1", "1002":"val2"} +} + +func ExampleIntAnyMap_FilterEmpty() { + m := gmap.NewIntAnyMapFrom(g.MapIntAny{ + 1: "", + 2: nil, + 3: 0, + 4: 1, + }) + m.FilterEmpty() + fmt.Println(m.Map()) + + // Output: + // map[4:1] +} + +func ExampleIntAnyMap_FilterNil() { + m := gmap.NewIntAnyMapFrom(g.MapIntAny{ + 1: "", + 2: nil, + 3: 0, + 4: 1, + }) + m.FilterNil() + fmt.Printf("%#v", m.Map()) + + // Output: + // map[int]interface {}{1:"", 3:0, 4:1} +} + +func ExampleIntAnyMap_Set() { + m := gmap.NewIntAnyMap() + + m.Set(1, "val1") + fmt.Println(m) + + // Output: + // {"1":"val1"} +} + +func ExampleIntAnyMap_Sets() { + m := gmap.NewIntAnyMap() + + addMap := make(map[int]interface{}) + addMap[1] = "val1" + addMap[2] = "val2" + addMap[3] = "val3" + + m.Sets(addMap) + fmt.Println(m) + + // Output: + // {"1":"val1","2":"val2","3":"val3"} +} + +func ExampleIntAnyMap_Search() { + m := gmap.NewIntAnyMap() + + m.Set(1, "val1") + + value, found := m.Search(1) + if found { + fmt.Println("find key1 value:", value) + } + + value, found = m.Search(2) + if !found { + fmt.Println("key2 not find") + } + + // Output: + // find key1 value: val1 + // key2 not find +} + +func ExampleIntAnyMap_Get() { + m := gmap.NewIntAnyMap() + + m.Set(1, "val1") + + fmt.Println("key1 value:", m.Get(1)) + fmt.Println("key2 value:", m.Get(2)) + + // Output: + // key1 value: val1 + // key2 value: +} + +func ExampleIntAnyMap_Pop() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + + fmt.Println(m.Pop()) + + // May Output: + // 1 v1 +} + +func ExampleIntAnyMap_Pops() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + fmt.Println(m.Pops(-1)) + fmt.Println("size:", m.Size()) + + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + fmt.Println(m.Pops(2)) + fmt.Println("size:", m.Size()) + + // May Output: + // map[1:v1 2:v2 3:v3 4:v4] + // size: 0 + // map[1:v1 2:v2] + // size: 2 +} + +func ExampleIntAnyMap_GetOrSet() { + m := gmap.NewIntAnyMap() + m.Set(1, "val1") + + fmt.Println(m.GetOrSet(1, "NotExistValue")) + fmt.Println(m.GetOrSet(2, "val2")) + + // Output: + // val1 + // val2 +} + +func ExampleIntAnyMap_GetOrSetFunc() { + m := gmap.NewIntAnyMap() + m.Set(1, "val1") + + fmt.Println(m.GetOrSetFunc(1, func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFunc(2, func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleIntAnyMap_GetOrSetFuncLock() { + m := gmap.NewIntAnyMap() + m.Set(1, "val1") + + fmt.Println(m.GetOrSetFuncLock(1, func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFuncLock(2, func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleIntAnyMap_GetVar() { + m := gmap.NewIntAnyMap() + m.Set(1, "val1") + + fmt.Println(m.GetVar(1)) + fmt.Println(m.GetVar(2).IsNil()) + + // Output: + // val1 + // true +} + +func ExampleIntAnyMap_GetVarOrSet() { + m := gmap.NewIntAnyMap() + m.Set(1, "val1") + + fmt.Println(m.GetVarOrSet(1, "NotExistValue")) + fmt.Println(m.GetVarOrSet(2, "val2")) + + // Output: + // val1 + // val2 +} + +func ExampleIntAnyMap_GetVarOrSetFunc() { + m := gmap.NewIntAnyMap() + m.Set(1, "val1") + + fmt.Println(m.GetVarOrSetFunc(1, func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetVarOrSetFunc(2, func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleIntAnyMap_GetVarOrSetFuncLock() { + m := gmap.NewIntAnyMap() + m.Set(1, "val1") + + fmt.Println(m.GetVarOrSetFuncLock(1, func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetVarOrSetFuncLock(2, func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleIntAnyMap_SetIfNotExist() { + var m gmap.IntAnyMap + fmt.Println(m.SetIfNotExist(1, "v1")) + fmt.Println(m.SetIfNotExist(1, "v2")) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[1:v1] +} + +func ExampleIntAnyMap_SetIfNotExistFunc() { + var m gmap.IntAnyMap + fmt.Println(m.SetIfNotExistFunc(1, func() interface{} { + return "v1" + })) + fmt.Println(m.SetIfNotExistFunc(1, func() interface{} { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[1:v1] +} + +func ExampleIntAnyMap_SetIfNotExistFuncLock() { + var m gmap.IntAnyMap + fmt.Println(m.SetIfNotExistFuncLock(1, func() interface{} { + return "v1" + })) + fmt.Println(m.SetIfNotExistFuncLock(1, func() interface{} { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[1:v1] +} + +func ExampleIntAnyMap_Remove() { + var m gmap.IntAnyMap + m.Set(1, "v1") + + fmt.Println(m.Remove(1)) + fmt.Println(m.Remove(2)) + fmt.Println(m.Size()) + + // Output: + // v1 + // + // 0 +} + +func ExampleIntAnyMap_Removes() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + + removeList := make([]int, 2) + removeList = append(removeList, 1) + removeList = append(removeList, 2) + + m.Removes(removeList) + + fmt.Println(m.Map()) + + // Output: + // map[3:v3 4:v4] +} + +func ExampleIntAnyMap_Keys() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + fmt.Println(m.Keys()) + + // May Output: + // [1 2 3 4] +} + +func ExampleIntAnyMap_Values() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + fmt.Println(m.Values()) + + // May Output: + // [v1 v2 v3 v4] +} + +func ExampleIntAnyMap_Contains() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + + fmt.Println(m.Contains(1)) + fmt.Println(m.Contains(5)) + + // Output: + // true + // false +} + +func ExampleIntAnyMap_Size() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + + fmt.Println(m.Size()) + + // Output: + // 4 +} + +func ExampleIntAnyMap_IsEmpty() { + var m gmap.IntAnyMap + fmt.Println(m.IsEmpty()) + + m.Set(1, "v1") + fmt.Println(m.IsEmpty()) + + // Output: + // true + // false +} + +func ExampleIntAnyMap_Clear() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + + m.Clear() + + fmt.Println(m.Map()) + + // Output: + // map[] +} + +func ExampleIntAnyMap_Replace() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + }) + + var n gmap.IntAnyMap + n.Sets(g.MapIntAny{ + 2: "v2", + }) + + fmt.Println(m.Map()) + + m.Replace(n.Map()) + fmt.Println(m.Map()) + + n.Set(2, "v1") + fmt.Println(m.Map()) + + // Output: + // map[1:v1] + // map[2:v2] + // map[2:v1] +} + +func ExampleIntAnyMap_LockFunc() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + m.LockFunc(func(m map[int]interface{}) { + totalValue := 0 + for _, v := range m { + totalValue += v.(int) + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 +} + +func ExampleIntAnyMap_RLockFunc() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + m.RLockFunc(func(m map[int]interface{}) { + totalValue := 0 + for _, v := range m { + totalValue += v.(int) + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 +} + +func ExampleIntAnyMap_Flip() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: 10, + }) + m.Flip() + fmt.Println(m.Map()) + + // Output: + // map[10:1] +} + +func ExampleIntAnyMap_Merge() { + var m1, m2 gmap.Map + m1.Set(1, "val1") + m2.Set(2, "val2") + m1.Merge(&m2) + fmt.Println(m1.Map()) + + // May Output: + // map[key1:val1 key2:val2] +} + +func ExampleIntAnyMap_String() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + }) + + fmt.Println(m.String()) + + // Output: + // {"1":"v1"} +} + +func ExampleIntAnyMap_MarshalJSON() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + + bytes, err := json.Marshal(&m) + if err == nil { + fmt.Println(gconv.String(bytes)) + } + + // Output: + // {"1":"v1","2":"v2","3":"v3","4":"v4"} +} + +func ExampleIntAnyMap_UnmarshalJSON() { + var m gmap.IntAnyMap + m.Sets(g.MapIntAny{ + 1: "v1", + 2: "v2", + 3: "v3", + 4: "v4", + }) + + var n gmap.Map + + err := json.Unmarshal(gconv.Bytes(m.String()), &n) + if err == nil { + fmt.Println(n.Map()) + } + + // Output: + // map[1:v1 2:v2 3:v3 4:v4] +} + +func ExampleIntAnyMap_UnmarshalValue() { + var m gmap.IntAnyMap + + goWeb := map[int]interface{}{ + 1: "goframe", + 2: "gin", + 3: "echo", + } + + if err := gconv.Scan(goWeb, &m); err == nil { + fmt.Printf("%#v", m.Map()) + } + + // Output: + // map[int]interface {}{1:"goframe", 2:"gin", 3:"echo"} +} diff --git a/container/gmap/gmap_z_example_int_int_test.go b/container/gmap/gmap_z_example_int_int_test.go new file mode 100644 index 00000000000..fb8f36f91d8 --- /dev/null +++ b/container/gmap/gmap_z_example_int_int_test.go @@ -0,0 +1,588 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with gm file, +// You can obtain one at https://github.com/gogf/gf. + +package gmap_test + +import ( + "fmt" + "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/util/gconv" +) + +func ExampleIntIntMap_Iterator() { + m := gmap.NewIntIntMap() + for i := 0; i < 10; i++ { + m.Set(i, i*2) + } + + var totalKey, totalValue int + m.Iterator(func(k int, v int) bool { + totalKey += k + totalValue += v + + return totalKey < 10 + }) + + fmt.Println("totalKey:", totalKey) + fmt.Println("totalValue:", totalValue) + + // May Output: + // totalKey: 11 + // totalValue: 22 +} + +func ExampleIntIntMap_Clone() { + m := gmap.NewIntIntMap() + + m.Set(1, 1) + fmt.Println(m) + + n := m.Clone() + fmt.Println(n) + + // Output: + // {"1":1} + // {"1":1} +} + +func ExampleIntIntMap_Map() { + // non concurrent-safety, a pointer to the underlying data + m1 := gmap.NewIntIntMap() + m1.Set(1, 1) + fmt.Println("m1:", m1) + + n1 := m1.Map() + fmt.Println("before n1:", n1) + m1.Set(1, 2) + fmt.Println("after n1:", n1) + + // concurrent-safety, copy of underlying data + m2 := gmap.New(true) + m2.Set(1, "1") + fmt.Println("m2:", m2) + + n2 := m2.Map() + fmt.Println("before n2:", n2) + m2.Set(1, "2") + fmt.Println("after n2:", n2) + + // Output: + // m1: {"1":1} + // before n1: map[1:1] + // after n1: map[1:2] + // m2: {"1":"1"} + // before n2: map[1:1] + // after n2: map[1:1] +} + +func ExampleIntIntMap_MapCopy() { + m := gmap.NewIntIntMap() + + m.Set(1, 1) + m.Set(2, 2) + fmt.Println(m) + + n := m.MapCopy() + fmt.Println(n) + + // Output: + // {"1":1,"2":2} + // map[1:1 2:2] +} + +func ExampleIntIntMap_MapStrAny() { + m := gmap.NewIntIntMap() + m.Set(1001, 1) + m.Set(1002, 2) + + n := m.MapStrAny() + fmt.Printf("%#v", n) + + // Output: + // map[string]interface {}{"1001":1, "1002":2} +} + +func ExampleIntIntMap_FilterEmpty() { + m := gmap.NewIntIntMapFrom(g.MapIntInt{ + 1: 0, + 2: 1, + }) + m.FilterEmpty() + fmt.Println(m.Map()) + + // Output: + // map[2:1] +} + +func ExampleIntIntMap_Set() { + m := gmap.NewIntIntMap() + + m.Set(1, 1) + fmt.Println(m) + + // Output: + // {"1":1} +} + +func ExampleIntIntMap_Sets() { + m := gmap.NewIntIntMap() + + addMap := make(map[int]int) + addMap[1] = 1 + addMap[2] = 12 + addMap[3] = 123 + + m.Sets(addMap) + fmt.Println(m) + + // Output: + // {"1":1,"2":12,"3":123} +} + +func ExampleIntIntMap_Search() { + m := gmap.NewIntIntMap() + + m.Set(1, 1) + + value, found := m.Search(1) + if found { + fmt.Println("find key1 value:", value) + } + + value, found = m.Search(2) + if !found { + fmt.Println("key2 not find") + } + + // Output: + // find key1 value: 1 + // key2 not find +} + +func ExampleIntIntMap_Get() { + m := gmap.NewIntIntMap() + + m.Set(1, 1) + + fmt.Println("key1 value:", m.Get(1)) + fmt.Println("key2 value:", m.Get(2)) + + // Output: + // key1 value: 1 + // key2 value: 0 +} + +func ExampleIntIntMap_Pop() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + fmt.Println(m.Pop()) + + // May Output: + // 1 1 +} + +func ExampleIntIntMap_Pops() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + fmt.Println(m.Pops(-1)) + fmt.Println("size:", m.Size()) + + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + fmt.Println(m.Pops(2)) + fmt.Println("size:", m.Size()) + + // May Output: + // map[1:1 2:2 3:3 4:4] + // size: 0 + // map[1:1 2:2] + // size: 2 +} + +func ExampleIntIntMap_GetOrSet() { + m := gmap.NewIntIntMap() + m.Set(1, 1) + + fmt.Println(m.GetOrSet(1, 0)) + fmt.Println(m.GetOrSet(2, 2)) + + // Output: + // 1 + // 2 +} + +func ExampleIntIntMap_GetOrSetFunc() { + m := gmap.NewIntIntMap() + m.Set(1, 1) + + fmt.Println(m.GetOrSetFunc(1, func() int { + return 0 + })) + fmt.Println(m.GetOrSetFunc(2, func() int { + return 0 + })) + + // Output: + // 1 + // 0 +} + +func ExampleIntIntMap_GetOrSetFuncLock() { + m := gmap.NewIntIntMap() + m.Set(1, 1) + + fmt.Println(m.GetOrSetFuncLock(1, func() int { + return 0 + })) + fmt.Println(m.GetOrSetFuncLock(2, func() int { + return 0 + })) + + // Output: + // 1 + // 0 +} + +func ExampleIntIntMap_SetIfNotExist() { + var m gmap.IntIntMap + fmt.Println(m.SetIfNotExist(1, 1)) + fmt.Println(m.SetIfNotExist(1, 2)) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[1:1] +} + +func ExampleIntIntMap_SetIfNotExistFunc() { + var m gmap.IntIntMap + fmt.Println(m.SetIfNotExistFunc(1, func() int { + return 1 + })) + fmt.Println(m.SetIfNotExistFunc(1, func() int { + return 2 + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[1:1] +} + +func ExampleIntIntMap_SetIfNotExistFuncLock() { + var m gmap.IntIntMap + fmt.Println(m.SetIfNotExistFuncLock(1, func() int { + return 1 + })) + fmt.Println(m.SetIfNotExistFuncLock(1, func() int { + return 2 + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[1:1] +} + +func ExampleIntIntMap_Remove() { + var m gmap.IntIntMap + m.Set(1, 1) + + fmt.Println(m.Remove(1)) + fmt.Println(m.Remove(2)) + fmt.Println(m.Size()) + + // Output: + // 1 + // 0 + // 0 +} + +func ExampleIntIntMap_Removes() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + removeList := make([]int, 2) + removeList = append(removeList, 1) + removeList = append(removeList, 2) + + m.Removes(removeList) + + fmt.Println(m.Map()) + + // Output: + // map[3:3 4:4] +} + +func ExampleIntIntMap_Keys() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + fmt.Println(m.Keys()) + + // May Output: + // [1 2 3 4] +} + +func ExampleIntIntMap_Values() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + fmt.Println(m.Values()) + + // May Output: + // [1 v2 v3 4] +} + +func ExampleIntIntMap_Contains() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + fmt.Println(m.Contains(1)) + fmt.Println(m.Contains(5)) + + // Output: + // true + // false +} + +func ExampleIntIntMap_Size() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + fmt.Println(m.Size()) + + // Output: + // 4 +} + +func ExampleIntIntMap_IsEmpty() { + var m gmap.IntIntMap + fmt.Println(m.IsEmpty()) + + m.Set(1, 1) + fmt.Println(m.IsEmpty()) + + // Output: + // true + // false +} + +func ExampleIntIntMap_Clear() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + m.Clear() + + fmt.Println(m.Map()) + + // Output: + // map[] +} + +func ExampleIntIntMap_Replace() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + }) + + var n gmap.IntIntMap + n.Sets(g.MapIntInt{ + 2: 2, + }) + + fmt.Println(m.Map()) + + m.Replace(n.Map()) + fmt.Println(m.Map()) + + n.Set(2, 1) + fmt.Println(m.Map()) + + // Output: + // map[1:1] + // map[2:2] + // map[2:1] +} + +func ExampleIntIntMap_LockFunc() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + m.LockFunc(func(m map[int]int) { + totalValue := 0 + for _, v := range m { + totalValue += v + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 +} + +func ExampleIntIntMap_RLockFunc() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + m.RLockFunc(func(m map[int]int) { + totalValue := 0 + for _, v := range m { + totalValue += v + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 +} + +func ExampleIntIntMap_Flip() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 10, + }) + m.Flip() + fmt.Println(m.Map()) + + // Output: + // map[10:1] +} + +func ExampleIntIntMap_Merge() { + var m1, m2 gmap.Map + m1.Set(1, "1") + m2.Set(2, "2") + m1.Merge(&m2) + fmt.Println(m1.Map()) + + // May Output: + // map[key1:1 key2:2] +} + +func ExampleIntIntMap_String() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + }) + + fmt.Println(m.String()) + + // Output: + // {"1":1} +} + +func ExampleIntIntMap_MarshalJSON() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + bytes, err := json.Marshal(&m) + if err == nil { + fmt.Println(gconv.String(bytes)) + } + + // Output: + // {"1":1,"2":2,"3":3,"4":4} +} + +func ExampleIntIntMap_UnmarshalJSON() { + var m gmap.IntIntMap + m.Sets(g.MapIntInt{ + 1: 1, + 2: 2, + 3: 3, + 4: 4, + }) + + var n gmap.Map + + err := json.Unmarshal(gconv.Bytes(m.String()), &n) + if err == nil { + fmt.Println(n.Map()) + } + + // Output: + // map[1:1 2:2 3:3 4:4] +} + +func ExampleIntIntMap_UnmarshalValue() { + var m gmap.IntIntMap + + n := map[int]int{ + 1: 1001, + 2: 1002, + 3: 1003, + } + + if err := gconv.Scan(n, &m); err == nil { + fmt.Printf("%#v", m.Map()) + } + // Output: + // map[int]int{1:1001, 2:1002, 3:1003} +} diff --git a/container/gmap/gmap_z_example_list_test.go b/container/gmap/gmap_z_example_list_test.go new file mode 100644 index 00000000000..0f6645d5002 --- /dev/null +++ b/container/gmap/gmap_z_example_list_test.go @@ -0,0 +1,624 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with gm file, +// You can obtain one at https://github.com/gogf/gf. + +package gmap_test + +import ( + "fmt" + "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/util/gconv" +) + +func ExampleListMap_Iterator() { + m := gmap.NewListMap() + for i := 0; i < 10; i++ { + m.Set(i, i*2) + } + + var totalKey, totalValue int + m.Iterator(func(k interface{}, v interface{}) bool { + totalKey += k.(int) + totalValue += v.(int) + + return totalKey < 10 + }) + + fmt.Println("totalKey:", totalKey) + fmt.Println("totalValue:", totalValue) + + // Output: + // totalKey: 10 + // totalValue: 20 +} + +func ExampleListMap_IteratorAsc() { + m := gmap.NewListMap() + for i := 0; i < 10; i++ { + m.Set(i, i*2) + } + + var totalKey, totalValue int + m.IteratorAsc(func(k interface{}, v interface{}) bool { + totalKey += k.(int) + totalValue += v.(int) + + return totalKey < 10 + }) + + fmt.Println("totalKey:", totalKey) + fmt.Println("totalValue:", totalValue) + + // Output: + // totalKey: 10 + // totalValue: 20 +} + +func ExampleListMap_IteratorDesc() { + m := gmap.NewListMap() + for i := 0; i < 10; i++ { + m.Set(i, i*2) + } + + var totalKey, totalValue int + m.IteratorDesc(func(k interface{}, v interface{}) bool { + totalKey += k.(int) + totalValue += v.(int) + + return totalKey < 10 + }) + + fmt.Println("totalKey:", totalKey) + fmt.Println("totalValue:", totalValue) + + // Output: + // totalKey: 17 + // totalValue: 34 +} + +func ExampleListMap_Clone() { + m := gmap.NewListMap() + + m.Set("key1", "val1") + fmt.Println(m) + + n := m.Clone() + fmt.Println(n) + + // Output: + // {"key1":"val1"} + // {"key1":"val1"} +} + +func ExampleListMap_Clear() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + m.Clear() + + fmt.Println(m.Map()) + + // Output: + // map[] +} + +func ExampleListMap_Replace() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + }) + + var n gmap.ListMap + n.Sets(g.MapAnyAny{ + "k2": "v2", + }) + + fmt.Println(m.Map()) + + m.Replace(n.Map()) + fmt.Println(m.Map()) + + // Output: + // map[k1:v1] + // map[k2:v2] +} + +func ExampleListMap_Map() { + m1 := gmap.NewListMap() + m1.Set("key1", "val1") + fmt.Println("m1:", m1) + + n1 := m1.Map() + fmt.Println("before n1:", n1) + m1.Set("key1", "val2") + fmt.Println("after n1:", n1) + + // Output: + // m1: {"key1":"val1"} + // before n1: map[key1:val1] + // after n1: map[key1:val1] +} + +func ExampleListMap_MapStrAny() { + m := gmap.NewListMap() + m.Set("key1", "val1") + m.Set("key2", "val2") + + n := m.MapStrAny() + fmt.Printf("%#v", n) + + // Output: + // map[string]interface {}{"key1":"val1", "key2":"val2"} +} + +func ExampleListMap_FilterEmpty() { + m := gmap.NewListMapFrom(g.MapAnyAny{ + "k1": "", + "k2": nil, + "k3": 0, + "k4": 1, + }) + m.FilterEmpty() + fmt.Println(m.Map()) + + // Output: + // map[k4:1] +} + +func ExampleListMap_Set() { + m := gmap.NewListMap() + + m.Set("key1", "val1") + fmt.Println(m) + + // Output: + // {"key1":"val1"} +} + +func ExampleListMap_Sets() { + m := gmap.NewListMap() + + addMap := make(map[interface{}]interface{}) + addMap["key1"] = "val1" + addMap["key2"] = "val2" + addMap["key3"] = "val3" + + m.Sets(addMap) + fmt.Println(m) + + // Output: + // {"key1":"val1","key2":"val2","key3":"val3"} +} + +func ExampleListMap_Search() { + m := gmap.NewListMap() + + m.Set("key1", "val1") + + value, found := m.Search("key1") + if found { + fmt.Println("find key1 value:", value) + } + + value, found = m.Search("key2") + if !found { + fmt.Println("key2 not find") + } + + // Output: + // find key1 value: val1 + // key2 not find +} + +func ExampleListMap_Get() { + m := gmap.NewListMap() + + m.Set("key1", "val1") + + fmt.Println("key1 value:", m.Get("key1")) + fmt.Println("key2 value:", m.Get("key2")) + + // Output: + // key1 value: val1 + // key2 value: +} + +func ExampleListMap_Pop() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Pop()) + + // May Output: + // k1 v1 +} + +func ExampleListMap_Pops() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Pops(-1)) + fmt.Println("size:", m.Size()) + + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Pops(2)) + fmt.Println("size:", m.Size()) + + // May Output: + // map[k1:v1 k2:v2 k3:v3 k4:v4] + // size: 0 + // map[k1:v1 k2:v2] + // size: 2 +} + +func ExampleListMap_GetOrSet() { + m := gmap.NewListMap() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSet("key1", "NotExistValue")) + fmt.Println(m.GetOrSet("key2", "val2")) + + // Output: + // val1 + // val2 +} + +func ExampleListMap_GetOrSetFunc() { + m := gmap.NewListMap() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSetFunc("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFunc("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleListMap_GetOrSetFuncLock() { + m := gmap.NewListMap() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSetFuncLock("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFuncLock("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleListMap_GetVar() { + m := gmap.NewListMap() + m.Set("key1", "val1") + + fmt.Println(m.GetVar("key1")) + fmt.Println(m.GetVar("key2").IsNil()) + + // Output: + // val1 + // true +} + +func ExampleListMap_GetVarOrSet() { + m := gmap.NewListMap() + m.Set("key1", "val1") + + fmt.Println(m.GetVarOrSet("key1", "NotExistValue")) + fmt.Println(m.GetVarOrSet("key2", "val2")) + + // Output: + // val1 + // val2 +} + +func ExampleListMap_GetVarOrSetFunc() { + m := gmap.NewListMap() + m.Set("key1", "val1") + + fmt.Println(m.GetVarOrSetFunc("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetVarOrSetFunc("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleListMap_GetVarOrSetFuncLock() { + m := gmap.NewListMap() + m.Set("key1", "val1") + + fmt.Println(m.GetVarOrSetFuncLock("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetVarOrSetFuncLock("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleListMap_SetIfNotExist() { + var m gmap.ListMap + fmt.Println(m.SetIfNotExist("k1", "v1")) + fmt.Println(m.SetIfNotExist("k1", "v2")) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleListMap_SetIfNotExistFunc() { + var m gmap.ListMap + fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + return "v1" + })) + fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleListMap_SetIfNotExistFuncLock() { + var m gmap.ListMap + fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + return "v1" + })) + fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleListMap_Remove() { + var m gmap.ListMap + m.Set("k1", "v1") + + fmt.Println(m.Remove("k1")) + fmt.Println(m.Remove("k2")) + fmt.Println(m.Size()) + + // Output: + // v1 + // + // 0 +} + +func ExampleListMap_Removes() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + removeList := make([]interface{}, 2) + removeList = append(removeList, "k1") + removeList = append(removeList, "k2") + + m.Removes(removeList) + + fmt.Println(m.Map()) + + // Output: + // map[k3:v3 k4:v4] +} + +func ExampleListMap_Keys() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Keys()) + + // May Output: + // [k1 k2 k3 k4] +} + +func ExampleListMap_Values() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Values()) + + // May Output: + // [v1 v2 v3 v4] +} + +func ExampleListMap_Contains() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Contains("k1")) + fmt.Println(m.Contains("k5")) + + // Output: + // true + // false +} + +func ExampleListMap_Size() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Size()) + + // Output: + // 4 +} + +func ExampleListMap_IsEmpty() { + var m gmap.ListMap + fmt.Println(m.IsEmpty()) + + m.Set("k1", "v1") + fmt.Println(m.IsEmpty()) + + // Output: + // true + // false +} + +func ExampleListMap_Flip() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + }) + m.Flip() + fmt.Println(m.Map()) + + // Output: + // map[v1:k1] +} + +func ExampleListMap_Merge() { + var m1, m2 gmap.ListMap + m1.Set("key1", "val1") + m2.Set("key2", "val2") + m1.Merge(&m2) + fmt.Println(m1.Map()) + + // May Output: + // map[key1:val1 key2:val2] +} + +func ExampleListMap_String() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + }) + + fmt.Println(m.String()) + + // Output: + // {"k1":"v1"} +} + +func ExampleListMap_MarshalJSON() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + bytes, err := json.Marshal(&m) + if err == nil { + fmt.Println(gconv.String(bytes)) + } + + // Output: + // {"k1":"v1","k2":"v2","k3":"v3","k4":"v4"} +} + +func ExampleListMap_UnmarshalJSON() { + var m gmap.ListMap + m.Sets(g.MapAnyAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + var n gmap.ListMap + + err := json.Unmarshal(gconv.Bytes(m.String()), &n) + if err == nil { + fmt.Println(n.Map()) + } + + // Output: + // map[k1:v1 k2:v2 k3:v3 k4:v4] +} + +func ExampleListMap_UnmarshalValue() { + type User struct { + Uid int + Name string + Pass1 string `gconv:"password1"` + Pass2 string `gconv:"password2"` + } + + var ( + m gmap.AnyAnyMap + user = User{ + Uid: 1, + Name: "john", + Pass1: "123", + Pass2: "456", + } + ) + if err := gconv.Scan(user, &m); err == nil { + fmt.Printf("%#v", m.Map()) + } + + // Output: + // map[interface {}]interface {}{"Name":"john", "Uid":1, "password1":"123", "password2":"456"} +} diff --git a/container/gmap/gmap_z_example_str_any_test.go b/container/gmap/gmap_z_example_str_any_test.go new file mode 100644 index 00000000000..bc34545a85f --- /dev/null +++ b/container/gmap/gmap_z_example_str_any_test.go @@ -0,0 +1,658 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with gm file, +// You can obtain one at https://github.com/gogf/gf. + +package gmap_test + +import ( + "fmt" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/util/gconv" + + "github.com/gogf/gf/v2/container/gmap" + "github.com/gogf/gf/v2/frame/g" +) + +func ExampleStrAnyMap_Iterator() { + m := gmap.NewStrAnyMap() + for i := 1; i <= 10; i++ { + m.Set(gconv.String(i), i*2) + } + + var totalValue int + m.Iterator(func(k string, v interface{}) bool { + totalValue += v.(int) + + return totalValue < 50 + }) + + fmt.Println("totalValue:", totalValue) + + // May Output: + // totalValue: 52 +} + +func ExampleStrAnyMap_Clone() { + m := gmap.NewStrAnyMap() + + m.Set("key1", "val1") + fmt.Println(m) + + n := m.Clone() + fmt.Println(n) + + // Output: + // {"key1":"val1"} + // {"key1":"val1"} +} + +func ExampleStrAnyMap_Map() { + // non concurrent-safety, a pointer to the underlying data + m1 := gmap.NewStrAnyMap() + m1.Set("key1", "val1") + fmt.Println("m1:", m1) + + n1 := m1.Map() + fmt.Println("before n1:", n1) + m1.Set("key1", "val2") + fmt.Println("after n1:", n1) + + // concurrent-safety, copy of underlying data + m2 := gmap.NewStrAnyMap(true) + m2.Set("key1", "val1") + fmt.Println("m2:", m2) + + n2 := m2.Map() + fmt.Println("before n2:", n2) + m2.Set("key1", "val2") + fmt.Println("after n2:", n2) + + // Output: + // m1: {"key1":"val1"} + // before n1: map[key1:val1] + // after n1: map[key1:val2] + // m2: {"key1":"val1"} + // before n2: map[key1:val1] + // after n2: map[key1:val1] +} + +func ExampleStrAnyMap_MapCopy() { + m := gmap.NewStrAnyMap() + + m.Set("key1", "val1") + m.Set("key2", "val2") + fmt.Println(m) + + n := m.MapCopy() + fmt.Println(n) + + // Output: + // {"key1":"val1","key2":"val2"} + // map[key1:val1 key2:val2] +} + +func ExampleStrAnyMap_MapStrAny() { + m := gmap.NewStrAnyMap() + m.Set("key1", "val1") + m.Set("key2", "val2") + + n := m.MapStrAny() + fmt.Printf("%#v", n) + + // Output: + // map[string]interface {}{"key1":"val1", "key2":"val2"} +} + +func ExampleStrAnyMap_FilterEmpty() { + m := gmap.NewStrAnyMapFrom(g.MapStrAny{ + "k1": "", + "k2": nil, + "k3": 0, + "k4": 1, + }) + m.FilterEmpty() + fmt.Println(m.Map()) + + // Output: + // map[k4:1] +} + +func ExampleStrAnyMap_FilterNil() { + m := gmap.NewStrAnyMapFrom(g.MapStrAny{ + "k1": "", + "k2": nil, + "k3": 0, + "k4": 1, + }) + m.FilterNil() + fmt.Printf("%#v", m.Map()) + + // Output: + // map[string]interface {}{"k1":"", "k3":0, "k4":1} +} + +func ExampleStrAnyMap_Set() { + m := gmap.NewStrAnyMap() + + m.Set("key1", "val1") + fmt.Println(m) + + // Output: + // {"key1":"val1"} +} + +func ExampleStrAnyMap_Sets() { + m := gmap.NewStrAnyMap() + + addMap := make(map[string]interface{}) + addMap["key1"] = "val1" + addMap["key2"] = "val2" + addMap["key3"] = "val3" + + m.Sets(addMap) + fmt.Println(m) + + // Output: + // {"key1":"val1","key2":"val2","key3":"val3"} +} + +func ExampleStrAnyMap_Search() { + m := gmap.NewStrAnyMap() + + m.Set("key1", "val1") + + value, found := m.Search("key1") + if found { + fmt.Println("find key1 value:", value) + } + + value, found = m.Search("key2") + if !found { + fmt.Println("key2 not find") + } + + // Output: + // find key1 value: val1 + // key2 not find +} + +func ExampleStrAnyMap_Get() { + m := gmap.NewStrAnyMap() + + m.Set("key1", "val1") + + fmt.Println("key1 value:", m.Get("key1")) + fmt.Println("key2 value:", m.Get("key2")) + + // Output: + // key1 value: val1 + // key2 value: +} + +func ExampleStrAnyMap_Pop() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Pop()) + + // May Output: + // k1 v1 +} + +func ExampleStrAnyMap_Pops() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Pops(-1)) + fmt.Println("size:", m.Size()) + + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Pops(2)) + fmt.Println("size:", m.Size()) + + // May Output: + // map[k1:v1 k2:v2 k3:v3 k4:v4] + // size: 0 + // map[k1:v1 k2:v2] + // size: 2 +} + +func ExampleStrAnyMap_GetOrSet() { + m := gmap.NewStrAnyMap() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSet("key1", "NotExistValue")) + fmt.Println(m.GetOrSet("key2", "val2")) + + // Output: + // val1 + // val2 +} + +func ExampleStrAnyMap_GetOrSetFunc() { + m := gmap.NewStrAnyMap() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSetFunc("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFunc("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleStrAnyMap_GetOrSetFuncLock() { + m := gmap.NewStrAnyMap() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSetFuncLock("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFuncLock("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleStrAnyMap_GetVar() { + m := gmap.NewStrAnyMap() + m.Set("key1", "val1") + + fmt.Println(m.GetVar("key1")) + fmt.Println(m.GetVar("key2").IsNil()) + + // Output: + // val1 + // true +} + +func ExampleStrAnyMap_GetVarOrSet() { + m := gmap.NewStrAnyMap() + m.Set("key1", "val1") + + fmt.Println(m.GetVarOrSet("key1", "NotExistValue")) + fmt.Println(m.GetVarOrSet("key2", "val2")) + + // Output: + // val1 + // val2 +} + +func ExampleStrAnyMap_GetVarOrSetFunc() { + m := gmap.NewStrAnyMap() + m.Set("key1", "val1") + + fmt.Println(m.GetVarOrSetFunc("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetVarOrSetFunc("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleStrAnyMap_GetVarOrSetFuncLock() { + m := gmap.NewStrAnyMap() + m.Set("key1", "val1") + + fmt.Println(m.GetVarOrSetFuncLock("key1", func() interface{} { + return "NotExistValue" + })) + fmt.Println(m.GetVarOrSetFuncLock("key2", func() interface{} { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleStrAnyMap_SetIfNotExist() { + var m gmap.StrAnyMap + fmt.Println(m.SetIfNotExist("k1", "v1")) + fmt.Println(m.SetIfNotExist("k1", "v2")) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleStrAnyMap_SetIfNotExistFunc() { + var m gmap.StrAnyMap + fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + return "v1" + })) + fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleStrAnyMap_SetIfNotExistFuncLock() { + var m gmap.StrAnyMap + fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + return "v1" + })) + fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleStrAnyMap_Remove() { + var m gmap.StrAnyMap + m.Set("k1", "v1") + + fmt.Println(m.Remove("k1")) + fmt.Println(m.Remove("k2")) + fmt.Println(m.Size()) + + // Output: + // v1 + // + // 0 +} + +func ExampleStrAnyMap_Removes() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + removeList := make([]string, 2) + removeList = append(removeList, "k1") + removeList = append(removeList, "k2") + + m.Removes(removeList) + + fmt.Println(m.Map()) + + // Output: + // map[k3:v3 k4:v4] +} + +func ExampleStrAnyMap_Keys() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Keys()) + + // May Output: + // [k1 k2 k3 k4] +} + +func ExampleStrAnyMap_Values() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Values()) + + // May Output: + // [v1 v2 v3 v4] +} + +func ExampleStrAnyMap_Contains() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Contains("k1")) + fmt.Println(m.Contains("k5")) + + // Output: + // true + // false +} + +func ExampleStrAnyMap_Size() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Size()) + + // Output: + // 4 +} + +func ExampleStrAnyMap_IsEmpty() { + var m gmap.StrAnyMap + fmt.Println(m.IsEmpty()) + + m.Set("k1", "v1") + fmt.Println(m.IsEmpty()) + + // Output: + // true + // false +} + +func ExampleStrAnyMap_Clear() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + m.Clear() + + fmt.Println(m.Map()) + + // Output: + // map[] +} + +func ExampleStrAnyMap_Replace() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + }) + + var n gmap.StrAnyMap + n.Sets(g.MapStrAny{ + "k2": "v2", + }) + + fmt.Println(m.Map()) + + m.Replace(n.Map()) + fmt.Println(m.Map()) + + n.Set("k2", "v1") + fmt.Println(m.Map()) + + // Output: + // map[k1:v1] + // map[k2:v2] + // map[k2:v1] +} + +func ExampleStrAnyMap_LockFunc() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + m.LockFunc(func(m map[string]interface{}) { + totalValue := 0 + for _, v := range m { + totalValue += v.(int) + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 +} + +func ExampleStrAnyMap_RLockFunc() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + m.RLockFunc(func(m map[string]interface{}) { + totalValue := 0 + for _, v := range m { + totalValue += v.(int) + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 +} + +func ExampleStrAnyMap_Flip() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + }) + m.Flip() + fmt.Println(m.Map()) + + // Output: + // map[v1:k1] +} + +func ExampleStrAnyMap_Merge() { + var m1, m2 gmap.StrAnyMap + m1.Set("key1", "val1") + m2.Set("key2", "val2") + m1.Merge(&m2) + fmt.Println(m1.Map()) + + // May Output: + // map[key1:val1 key2:val2] +} + +func ExampleStrAnyMap_String() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + }) + + fmt.Println(m.String()) + + // Output: + // {"k1":"v1"} +} + +func ExampleStrAnyMap_MarshalJSON() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + bytes, err := json.Marshal(&m) + if err == nil { + fmt.Println(gconv.String(bytes)) + } + + // Output: + // {"k1":"v1","k2":"v2","k3":"v3","k4":"v4"} +} + +func ExampleStrAnyMap_UnmarshalJSON() { + var m gmap.StrAnyMap + m.Sets(g.MapStrAny{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + var n gmap.StrAnyMap + + err := json.Unmarshal(gconv.Bytes(m.String()), &n) + if err == nil { + fmt.Println(n.Map()) + } + + // Output: + // map[k1:v1 k2:v2 k3:v3 k4:v4] +} + +func ExampleStrAnyMap_UnmarshalValue() { + var m gmap.StrAnyMap + + goWeb := map[string]interface{}{ + "goframe": "https://goframe.org", + "gin": "https://gin-gonic.com/", + "echo": "https://echo.labstack.com/", + } + + if err := gconv.Scan(goWeb, &m); err == nil { + fmt.Printf("%#v", m.Map()) + } + // Output: + // map[string]interface {}{"echo":"https://echo.labstack.com/", "gin":"https://gin-gonic.com/", "goframe":"https://goframe.org"} +} diff --git a/container/gmap/gmap_z_example_str_int_test.go b/container/gmap/gmap_z_example_str_int_test.go new file mode 100644 index 00000000000..bdd2f5eac56 --- /dev/null +++ b/container/gmap/gmap_z_example_str_int_test.go @@ -0,0 +1,594 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with gm file, +// You can obtain one at https://github.com/gogf/gf. + +package gmap_test + +import ( + "fmt" + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/util/gconv" + + "github.com/gogf/gf/v2/container/gmap" +) + +func ExampleStrIntMap_Iterator() { + m := gmap.NewStrIntMap() + for i := 0; i < 10; i++ { + m.Set(gconv.String(i), i*2) + } + + var totalValue int + m.Iterator(func(k string, v int) bool { + totalValue += v + + return totalValue < 50 + }) + + fmt.Println("totalValue:", totalValue) + + // May Output: + // totalValue: 52 +} + +func ExampleStrIntMap_Clone() { + m := gmap.NewStrIntMap() + + m.Set("key1", 1) + fmt.Println(m) + + n := m.Clone() + fmt.Println(n) + + // Output: + // {"key1":1} + // {"key1":1} +} + +func ExampleStrIntMap_Map() { + // non concurrent-safety, a pointer to the underlying data + m1 := gmap.NewStrIntMap() + m1.Set("key1", 1) + fmt.Println("m1:", m1) + + n1 := m1.Map() + fmt.Println("before n1:", n1) + m1.Set("key1", 2) + fmt.Println("after n1:", n1) + + // concurrent-safety, copy of underlying data + m2 := gmap.NewStrIntMap(true) + m2.Set("key1", 1) + fmt.Println("m2:", m2) + + n2 := m2.Map() + fmt.Println("before n2:", n2) + m2.Set("key1", 2) + fmt.Println("after n2:", n2) + + // Output: + // m1: {"key1":1} + // before n1: map[key1:1] + // after n1: map[key1:2] + // m2: {"key1":1} + // before n2: map[key1:1] + // after n2: map[key1:1] +} + +func ExampleStrIntMap_MapCopy() { + m := gmap.NewStrIntMap() + + m.Set("key1", 1) + m.Set("key2", 2) + fmt.Println(m) + + n := m.MapCopy() + fmt.Println(n) + + // Output: + // {"key1":1,"key2":2} + // map[key1:1 key2:2] +} + +func ExampleStrIntMap_MapStrAny() { + m := gmap.NewStrIntMap() + m.Set("key1", 1) + m.Set("key2", 2) + + n := m.MapStrAny() + fmt.Printf("%#v", n) + + // Output: + // map[string]interface {}{"key1":1, "key2":2} +} + +func ExampleStrIntMap_FilterEmpty() { + m := gmap.NewStrIntMapFrom(g.MapStrInt{ + "k1": 0, + "k2": 1, + }) + m.FilterEmpty() + fmt.Println(m.Map()) + + // Output: + // map[k2:1] +} + +func ExampleStrIntMap_Set() { + m := gmap.NewStrIntMap() + + m.Set("key1", 1) + fmt.Println(m) + + // Output: + // {"key1":1} +} + +func ExampleStrIntMap_Sets() { + m := gmap.NewStrIntMap() + + addMap := make(map[string]int) + addMap["key1"] = 1 + addMap["key2"] = 2 + addMap["key3"] = 3 + + m.Sets(addMap) + fmt.Println(m) + + // Output: + // {"key1":1,"key2":2,"key3":3} +} + +func ExampleStrIntMap_Search() { + m := gmap.NewStrIntMap() + + m.Set("key1", 1) + + value, found := m.Search("key1") + if found { + fmt.Println("find key1 value:", value) + } + + value, found = m.Search("key2") + if !found { + fmt.Println("key2 not find") + } + + // Output: + // find key1 value: 1 + // key2 not find +} + +func ExampleStrIntMap_Get() { + m := gmap.NewStrIntMap() + + m.Set("key1", 1) + + fmt.Println("key1 value:", m.Get("key1")) + fmt.Println("key2 value:", m.Get("key2")) + + // Output: + // key1 value: 1 + // key2 value: 0 +} + +func ExampleStrIntMap_Pop() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + fmt.Println(m.Pop()) + + // May Output: + // k1 1 +} + +func ExampleStrIntMap_Pops() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + fmt.Println(m.Pops(-1)) + fmt.Println("size:", m.Size()) + + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + fmt.Println(m.Pops(2)) + fmt.Println("size:", m.Size()) + + // May Output: + // map[k1:1 k2:2 k3:3 k4:4] + // size: 0 + // map[k1:1 k2:2] + // size: 2 +} + +func ExampleStrIntMap_GetOrSet() { + m := gmap.NewStrIntMap() + m.Set("key1", 1) + + fmt.Println(m.GetOrSet("key1", 0)) + fmt.Println(m.GetOrSet("key2", 2)) + + // Output: + // 1 + // 2 +} + +func ExampleStrIntMap_GetOrSetFunc() { + m := gmap.NewStrIntMap() + m.Set("key1", 1) + + fmt.Println(m.GetOrSetFunc("key1", func() int { + return 0 + })) + fmt.Println(m.GetOrSetFunc("key2", func() int { + return 0 + })) + + // Output: + // 1 + // 0 +} + +func ExampleStrIntMap_GetOrSetFuncLock() { + m := gmap.NewStrIntMap() + m.Set("key1", 1) + + fmt.Println(m.GetOrSetFuncLock("key1", func() int { + return 0 + })) + fmt.Println(m.GetOrSetFuncLock("key2", func() int { + return 0 + })) + + // Output: + // 1 + // 0 +} + +func ExampleStrIntMap_SetIfNotExist() { + var m gmap.StrIntMap + fmt.Println(m.SetIfNotExist("k1", 1)) + fmt.Println(m.SetIfNotExist("k1", 2)) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:1] +} + +func ExampleStrIntMap_SetIfNotExistFunc() { + var m gmap.StrIntMap + fmt.Println(m.SetIfNotExistFunc("k1", func() int { + return 1 + })) + fmt.Println(m.SetIfNotExistFunc("k1", func() int { + return 2 + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:1] +} + +func ExampleStrIntMap_SetIfNotExistFuncLock() { + var m gmap.StrIntMap + fmt.Println(m.SetIfNotExistFuncLock("k1", func() int { + return 1 + })) + fmt.Println(m.SetIfNotExistFuncLock("k1", func() int { + return 2 + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:1] +} + +func ExampleStrIntMap_Remove() { + var m gmap.StrIntMap + m.Set("k1", 1) + + fmt.Println(m.Remove("k1")) + fmt.Println(m.Remove("k2")) + fmt.Println(m.Size()) + + // Output: + // 1 + // 0 + // 0 +} + +func ExampleStrIntMap_Removes() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + removeList := make([]string, 2) + removeList = append(removeList, "k1") + removeList = append(removeList, "k2") + + m.Removes(removeList) + + fmt.Println(m.Map()) + + // Output: + // map[k3:3 k4:4] +} + +func ExampleStrIntMap_Keys() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + fmt.Println(m.Keys()) + + // May Output: + // [k1 k2 k3 k4] +} + +func ExampleStrIntMap_Values() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + fmt.Println(m.Values()) + + // May Output: + // [1 2 3 4] +} + +func ExampleStrIntMap_Contains() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + fmt.Println(m.Contains("k1")) + fmt.Println(m.Contains("k5")) + + // Output: + // true + // false +} + +func ExampleStrIntMap_Size() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + fmt.Println(m.Size()) + + // Output: + // 4 +} + +func ExampleStrIntMap_IsEmpty() { + var m gmap.StrIntMap + fmt.Println(m.IsEmpty()) + + m.Set("k1", 1) + fmt.Println(m.IsEmpty()) + + // Output: + // true + // false +} + +func ExampleStrIntMap_Clear() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + m.Clear() + + fmt.Println(m.Map()) + + // Output: + // map[] +} + +func ExampleStrIntMap_Replace() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + }) + + var n gmap.StrIntMap + n.Sets(g.MapStrInt{ + "k2": 2, + }) + + fmt.Println(m.Map()) + + m.Replace(n.Map()) + fmt.Println(m.Map()) + + n.Set("k2", 1) + fmt.Println(m.Map()) + + // Output: + // map[k1:1] + // map[k2:2] + // map[k2:1] +} + +func ExampleStrIntMap_LockFunc() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + m.LockFunc(func(m map[string]int) { + totalValue := 0 + for _, v := range m { + totalValue += v + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 +} + +func ExampleStrIntMap_RLockFunc() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + m.RLockFunc(func(m map[string]int) { + totalValue := 0 + for _, v := range m { + totalValue += v + } + fmt.Println("totalValue:", totalValue) + }) + + // Output: + // totalValue: 10 +} + +func ExampleStrIntMap_Flip() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + }) + m.Flip() + fmt.Println(m.Map()) + + var n gmap.StrIntMap + n.Sets(g.MapStrInt{ + "11": 1, + }) + n.Flip() + fmt.Println(n.Map()) + + // Output: + // map[1:0] + // map[1:11] +} + +func ExampleStrIntMap_Merge() { + var m1, m2 gmap.StrIntMap + m1.Set("key1", 1) + m2.Set("key2", 2) + m1.Merge(&m2) + fmt.Println(m1.Map()) + + // May Output: + // map[key1:1 key2:2] +} + +func ExampleStrIntMap_String() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + }) + + fmt.Println(m.String()) + + // Output: + // {"k1":1} +} + +func ExampleStrIntMap_MarshalJSON() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + bytes, err := json.Marshal(&m) + if err == nil { + fmt.Println(gconv.String(bytes)) + } + + // Output: + // {"k1":1,"k2":2,"k3":3,"k4":4} +} + +func ExampleStrIntMap_UnmarshalJSON() { + var m gmap.StrIntMap + m.Sets(g.MapStrInt{ + "k1": 1, + "k2": 2, + "k3": 3, + "k4": 4, + }) + + var n gmap.StrIntMap + + err := json.Unmarshal(gconv.Bytes(m.String()), &n) + if err == nil { + fmt.Println(n.Map()) + } + + // Output: + // map[k1:1 k2:2 k3:3 k4:4] +} + +func ExampleStrIntMap_UnmarshalValue() { + var m gmap.StrIntMap + + goWeb := map[string]int{ + "goframe": 1, + "gin": 2, + "echo": 3, + } + + if err := gconv.Scan(goWeb, &m); err == nil { + fmt.Printf("%#v", m.Map()) + } + // Output: + // map[string]int{"echo":3, "gin":2, "goframe":1} +} diff --git a/container/gmap/gmap_z_example_str_str_test.go b/container/gmap/gmap_z_example_str_str_test.go new file mode 100644 index 00000000000..9ac5bee6df0 --- /dev/null +++ b/container/gmap/gmap_z_example_str_str_test.go @@ -0,0 +1,590 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with gm file, +// You can obtain one at https://github.com/gogf/gf. + +package gmap_test + +import ( + "fmt" + "github.com/gogf/gf/v2/internal/json" + + "github.com/gogf/gf/v2/frame/g" + "github.com/gogf/gf/v2/util/gconv" + + "github.com/gogf/gf/v2/container/gmap" +) + +func ExampleStrStrMap_Iterator() { + m := gmap.NewStrStrMap() + for i := 0; i < 10; i++ { + m.Set("key"+gconv.String(i), "var"+gconv.String(i)) + } + + var str string + m.Iterator(func(k string, v string) bool { + + str += v + "|" + + return len(str) < 20 + }) + + fmt.Println("str:", str) + + // May Output: + // var0|var1|var2|var3| +} + +func ExampleStrStrMap_Clone() { + m := gmap.NewStrStrMap() + + m.Set("key1", "val1") + fmt.Println(m) + + n := m.Clone() + fmt.Println(n) + + // Output: + // {"key1":"val1"} + // {"key1":"val1"} +} + +func ExampleStrStrMap_Map() { + // non concurrent-safety, a pointer to the underlying data + m1 := gmap.NewStrStrMap() + m1.Set("key1", "val1") + fmt.Println("m1:", m1) + + n1 := m1.Map() + fmt.Println("before n1:", n1) + m1.Set("key1", "val2") + fmt.Println("after n1:", n1) + + // concurrent-safety, copy of underlying data + m2 := gmap.NewStrStrMap(true) + m2.Set("key1", "val1") + fmt.Println("m2:", m2) + + n2 := m2.Map() + fmt.Println("before n2:", n2) + m2.Set("key1", "val2") + fmt.Println("after n2:", n2) + + // Output: + // m1: {"key1":"val1"} + // before n1: map[key1:val1] + // after n1: map[key1:val2] + // m2: {"key1":"val1"} + // before n2: map[key1:val1] + // after n2: map[key1:val1] +} + +func ExampleStrStrMap_MapCopy() { + m := gmap.NewStrStrMap() + + m.Set("key1", "val1") + m.Set("key2", "val2") + fmt.Println(m) + + n := m.MapCopy() + fmt.Println(n) + + // Output: + // {"key1":"val1","key2":"val2"} + // map[key1:val1 key2:val2] +} + +func ExampleStrStrMap_MapStrAny() { + m := gmap.NewStrStrMap() + m.Set("key1", "val1") + m.Set("key2", "val2") + + n := m.MapStrAny() + fmt.Printf("%#v", n) + + // Output: + // map[string]interface {}{"key1":"val1", "key2":"val2"} +} + +func ExampleStrStrMap_FilterEmpty() { + m := gmap.NewStrStrMapFrom(g.MapStrStr{ + "k1": "", + "k2": "v2", + }) + m.FilterEmpty() + fmt.Println(m.Map()) + + // Output: + // map[k2:v2] +} + +func ExampleStrStrMap_Set() { + m := gmap.NewStrStrMap() + + m.Set("key1", "val1") + fmt.Println(m) + + // Output: + // {"key1":"val1"} +} + +func ExampleStrStrMap_Sets() { + m := gmap.NewStrStrMap() + + addMap := make(map[string]string) + addMap["key1"] = "val1" + addMap["key2"] = "val2" + addMap["key3"] = "val3" + + m.Sets(addMap) + fmt.Println(m) + + // Output: + // {"key1":"val1","key2":"val2","key3":"val3"} +} + +func ExampleStrStrMap_Search() { + m := gmap.NewStrStrMap() + + m.Set("key1", "val1") + + value, found := m.Search("key1") + if found { + fmt.Println("find key1 value:", value) + } + + value, found = m.Search("key2") + if !found { + fmt.Println("key2 not find") + } + + // Output: + // find key1 value: val1 + // key2 not find +} + +func ExampleStrStrMap_Get() { + m := gmap.NewStrStrMap() + + m.Set("key1", "val1") + + fmt.Println("key1 value:", m.Get("key1")) + fmt.Println("key2 value:", m.Get("key2")) + + // Output: + // key1 value: val1 + // key2 value: +} + +func ExampleStrStrMap_Pop() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Pop()) + + // May Output: + // k1 v1 +} + +func ExampleStrStrMap_Pops() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Pops(-1)) + fmt.Println("size:", m.Size()) + + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Pops(2)) + fmt.Println("size:", m.Size()) + + // May Output: + // map[k1:v1 k2:v2 k3:v3 k4:v4] + // size: 0 + // map[k1:v1 k2:v2] + // size: 2 +} + +func ExampleStrStrMap_GetOrSet() { + m := gmap.NewStrStrMap() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSet("key1", "NotExistValue")) + fmt.Println(m.GetOrSet("key2", "val2")) + + // Output: + // val1 + // val2 +} + +func ExampleStrStrMap_GetOrSetFunc() { + m := gmap.NewStrStrMap() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSetFunc("key1", func() string { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFunc("key2", func() string { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleStrStrMap_GetOrSetFuncLock() { + m := gmap.NewStrStrMap() + m.Set("key1", "val1") + + fmt.Println(m.GetOrSetFuncLock("key1", func() string { + return "NotExistValue" + })) + fmt.Println(m.GetOrSetFuncLock("key2", func() string { + return "NotExistValue" + })) + + // Output: + // val1 + // NotExistValue +} + +func ExampleStrStrMap_SetIfNotExist() { + var m gmap.StrStrMap + fmt.Println(m.SetIfNotExist("k1", "v1")) + fmt.Println(m.SetIfNotExist("k1", "v2")) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleStrStrMap_SetIfNotExistFunc() { + var m gmap.StrStrMap + fmt.Println(m.SetIfNotExistFunc("k1", func() string { + return "v1" + })) + fmt.Println(m.SetIfNotExistFunc("k1", func() string { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleStrStrMap_SetIfNotExistFuncLock() { + var m gmap.StrStrMap + fmt.Println(m.SetIfNotExistFuncLock("k1", func() string { + return "v1" + })) + fmt.Println(m.SetIfNotExistFuncLock("k1", func() string { + return "v2" + })) + fmt.Println(m.Map()) + + // Output: + // true + // false + // map[k1:v1] +} + +func ExampleStrStrMap_Remove() { + var m gmap.StrStrMap + m.Set("k1", "v1") + + fmt.Println(m.Remove("k1")) + fmt.Println(len(m.Remove("k2"))) + fmt.Println(m.Size()) + + // Output: + // v1 + // 0 + // 0 +} + +func ExampleStrStrMap_Removes() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + removeList := make([]string, 2) + removeList = append(removeList, "k1") + removeList = append(removeList, "k2") + + m.Removes(removeList) + + fmt.Println(m.Map()) + + // Output: + // map[k3:v3 k4:v4] +} + +func ExampleStrStrMap_Keys() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Keys()) + + // May Output: + // [k1 k2 k3 k4] +} + +func ExampleStrStrMap_Values() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + fmt.Println(m.Values()) + + // May Output: + // [v1 v2 v3 v4] +} + +func ExampleStrStrMap_Contains() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Contains("k1")) + fmt.Println(m.Contains("k5")) + + // Output: + // true + // false +} + +func ExampleStrStrMap_Size() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + fmt.Println(m.Size()) + + // Output: + // 4 +} + +func ExampleStrStrMap_IsEmpty() { + var m gmap.StrStrMap + fmt.Println(m.IsEmpty()) + + m.Set("k1", "v1") + fmt.Println(m.IsEmpty()) + + // Output: + // true + // false +} + +func ExampleStrStrMap_Clear() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + m.Clear() + + fmt.Println(m.Map()) + + // Output: + // map[] +} + +func ExampleStrStrMap_Replace() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + }) + + var n gmap.StrStrMap + n.Sets(g.MapStrStr{ + "k2": "v2", + }) + + fmt.Println(m.Map()) + + m.Replace(n.Map()) + fmt.Println(m.Map()) + + n.Set("k2", "v1") + fmt.Println(m.Map()) + + // Output: + // map[k1:v1] + // map[k2:v2] + // map[k2:v1] +} + +func ExampleStrStrMap_LockFunc() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + m.LockFunc(func(m map[string]string) { + for k, v := range m { + fmt.Println("key:", k, " value:", v) + } + }) + + // May Output: + // key: k1 value: v1 + // key: k2 value: v2 + // key: k3 value: v3 + // key: k4 value: v4 +} + +func ExampleStrStrMap_RLockFunc() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + m.RLockFunc(func(m map[string]string) { + for k, v := range m { + fmt.Println("key:", k, " value:", v) + } + }) + + // May Output: + // key: k1 value: v1 + // key: k2 value: v2 + // key: k3 value: v3 + // key: k4 value: v4 +} + +func ExampleStrStrMap_Flip() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + }) + m.Flip() + fmt.Println(m.Map()) + + // Output: + // map[v1:k1] +} + +func ExampleStrStrMap_Merge() { + var m1, m2 gmap.StrStrMap + m1.Set("key1", "val1") + m2.Set("key2", "val2") + m1.Merge(&m2) + fmt.Println(m1.Map()) + + // May Output: + // map[key1:val1 key2:val2] +} + +func ExampleStrStrMap_String() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + }) + + fmt.Println(m.String()) + + // Output: + // {"k1":"v1"} +} + +func ExampleStrStrMap_MarshalJSON() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + bytes, err := json.Marshal(&m) + if err == nil { + fmt.Println(gconv.String(bytes)) + } + + // Output: + // {"k1":"v1","k2":"v2","k3":"v3","k4":"v4"} +} + +func ExampleStrStrMap_UnmarshalJSON() { + var m gmap.StrStrMap + m.Sets(g.MapStrStr{ + "k1": "v1", + "k2": "v2", + "k3": "v3", + "k4": "v4", + }) + + var n gmap.StrStrMap + + err := json.Unmarshal(gconv.Bytes(m.String()), &n) + if err == nil { + fmt.Println(n.Map()) + } + + // Output: + // map[k1:v1 k2:v2 k3:v3 k4:v4] +} + +func ExampleStrStrMap_UnmarshalValue() { + var m gmap.StrStrMap + + goWeb := map[string]string{ + "goframe": "https://goframe.org", + "gin": "https://gin-gonic.com/", + "echo": "https://echo.labstack.com/", + } + + if err := gconv.Scan(goWeb, &m); err == nil { + fmt.Printf("%#v", m.Map()) + } + // Output: + // map[string]string{"echo":"https://echo.labstack.com/", "gin":"https://gin-gonic.com/", "goframe":"https://goframe.org"} +} diff --git a/container/gmap/gmap_z_example_test.go b/container/gmap/gmap_z_example_test.go new file mode 100644 index 00000000000..4ef5fe3b41c --- /dev/null +++ b/container/gmap/gmap_z_example_test.go @@ -0,0 +1,311 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with gm file, +// You can obtain one at https://github.com/gogf/gf. + +package gmap_test + +import ( + "fmt" + "github.com/gogf/gf/v2/util/gutil" + + "github.com/gogf/gf/v2/container/gmap" +) + +func ExampleNew() { + m := gmap.New() + + // Add data. + m.Set("key1", "val1") + + // Print size. + fmt.Println(m.Size()) + + addMap := make(map[interface{}]interface{}) + addMap["key2"] = "val2" + addMap["key3"] = "val3" + addMap[1] = 1 + + fmt.Println(m.Values()) + + // Batch add data. + m.Sets(addMap) + + // Gets the value of the corresponding key. + fmt.Println(m.Get("key3")) + + // Get the value by key, or set it with given key-value if not exist. + fmt.Println(m.GetOrSet("key4", "val4")) + + // Set key-value if the key does not exist, then return true; or else return false. + fmt.Println(m.SetIfNotExist("key3", "val3")) + + // Remove key + m.Remove("key2") + fmt.Println(m.Keys()) + + // Batch remove keys. + m.Removes([]interface{}{"key1", 1}) + fmt.Println(m.Keys()) + + // Contains checks whether a key exists. + fmt.Println(m.Contains("key3")) + + // Flip exchanges key-value of the map, it will change key-value to value-key. + m.Flip() + fmt.Println(m.Map()) + + // Clear deletes all data of the map. + m.Clear() + + fmt.Println(m.Size()) + + // May Output: + // 1 + // [val1] + // val3 + // val4 + // false + // [key4 key1 key3 1] + // [key4 key3] + // true + // map[val3:key3 val4:key4] + // 0 +} + +func ExampleNewFrom() { + m := gmap.New() + + m.Set("key1", "val1") + fmt.Println(m) + + n := gmap.NewFrom(m.MapCopy(), true) + fmt.Println(n) + + // Output: + // {"key1":"val1"} + // {"key1":"val1"} +} + +func ExampleNewHashMap() { + m := gmap.New() + + m.Set("key1", "val1") + fmt.Println(m) + + // Output: + // {"key1":"val1"} +} + +func ExampleNewHashMapFrom() { + m := gmap.New() + + m.Set("key1", "val1") + fmt.Println(m) + + n := gmap.NewFrom(m.MapCopy(), true) + fmt.Println(n) + + // Output: + // {"key1":"val1"} + // {"key1":"val1"} +} + +func ExampleNewAnyAnyMap() { + m := gmap.NewAnyAnyMap() + + m.Set("key1", "val1") + fmt.Println(m) + + // Output: + // {"key1":"val1"} +} + +func ExampleNewAnyAnyMapFrom() { + m := gmap.NewAnyAnyMap() + + m.Set("key1", "val1") + fmt.Println(m) + + n := gmap.NewAnyAnyMapFrom(m.MapCopy(), true) + fmt.Println(n) + + // Output: + // {"key1":"val1"} + // {"key1":"val1"} +} + +func ExampleNewIntAnyMap() { + m := gmap.NewIntAnyMap() + + m.Set(1, "val1") + fmt.Println(m) + + // Output: + // {"1":"val1"} +} + +func ExampleNewIntAnyMapFrom() { + m := gmap.NewIntAnyMap() + + m.Set(1, "val1") + fmt.Println(m) + + n := gmap.NewIntAnyMapFrom(m.MapCopy(), true) + fmt.Println(n) + + // Output: + // {"1":"val1"} + // {"1":"val1"} +} + +func ExampleNewIntIntMap() { + m := gmap.NewIntIntMap() + + m.Set(1, 1) + fmt.Println(m) + + // Output: + // {"1":1} +} + +func ExampleNewIntIntMapFrom() { + m := gmap.NewIntIntMap() + + m.Set(1, 1) + fmt.Println(m) + + n := gmap.NewIntIntMapFrom(m.MapCopy(), true) + fmt.Println(n) + + // Output: + // {"1":1} + // {"1":1} +} + +func ExampleNewStrAnyMap() { + m := gmap.NewStrAnyMap() + + m.Set("key1", "var1") + fmt.Println(m) + + // Output: + // {"key1":"var1"} +} + +func ExampleNewStrAnyMapFrom() { + m := gmap.NewStrAnyMap() + + m.Set("key1", "var1") + fmt.Println(m) + + n := gmap.NewStrAnyMapFrom(m.MapCopy(), true) + fmt.Println(n) + + // Output: + // {"key1":"var1"} + // {"key1":"var1"} +} + +func ExampleNewStrIntMap() { + m := gmap.NewStrIntMap() + + m.Set("key1", 1) + fmt.Println(m) + + // Output: + // {"key1":1} +} + +func ExampleNewStrIntMapFrom() { + m := gmap.NewStrIntMap() + + m.Set("key1", 1) + fmt.Println(m) + + n := gmap.NewStrIntMapFrom(m.MapCopy(), true) + fmt.Println(n) + + // Output: + // {"key1":1} + // {"key1":1} +} + +func ExampleNewStrStrMap() { + m := gmap.NewStrStrMap() + + m.Set("key1", "var1") + fmt.Println(m) + + // Output: + // {"key1":"var1"} +} + +func ExampleNewStrStrMapFrom() { + m := gmap.NewStrStrMap() + + m.Set("key1", "var1") + fmt.Println(m) + + n := gmap.NewStrStrMapFrom(m.MapCopy(), true) + fmt.Println(n) + + // Output: + // {"key1":"var1"} + // {"key1":"var1"} +} + +func ExampleNewListMap() { + m := gmap.NewListMap() + + m.Set("key1", "var1") + m.Set("key2", "var2") + fmt.Println(m) + + // Output: + // {"key1":"var1","key2":"var2"} +} + +func ExampleNewListMapFrom() { + m := gmap.NewListMap() + + m.Set("key1", "var1") + m.Set("key2", "var2") + fmt.Println(m) + + n := gmap.NewListMapFrom(m.Map(), true) + fmt.Println(n) + + // Output: + // {"key1":"var1","key2":"var2"} + // {"key1":"var1","key2":"var2"} +} + +func ExampleNewTreeMap() { + m := gmap.NewTreeMap(gutil.ComparatorString) + + m.Set("key2", "var2") + m.Set("key1", "var1") + + fmt.Println(m.Map()) + + // Output: + // map[key1:var1 key2:var2] +} + +func ExampleNewTreeMapFrom() { + m := gmap.NewTreeMap(gutil.ComparatorString) + + m.Set("key2", "var2") + m.Set("key1", "var1") + + fmt.Println(m.Map()) + + n := gmap.NewListMapFrom(m.Map(), true) + fmt.Println(n.Map()) + + // Output: + // map[key1:var1 key2:var2] + // map[key1:var1 key2:var2] +} diff --git a/database/gdb/gdb_model_select.go b/database/gdb/gdb_model_select.go index 9e4006c61b7..3bd195c61e2 100644 --- a/database/gdb/gdb_model_select.go +++ b/database/gdb/gdb_model_select.go @@ -320,7 +320,12 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error { // // See Result.ScanList. func (m *Model) ScanList(structSlicePointer interface{}, bindToAttrName string, relationAttrNameAndFields ...string) (err error) { - result, err := m.All() + out, err := checkGetSliceElementInfoForScanList(structSlicePointer, bindToAttrName) + if err != nil { + return err + } + // Filter fields using temporary created struct using reflect.New. + result, err := m.Fields(reflect.New(out.BindToAttrType).Interface()).All() if err != nil { return err } @@ -335,7 +340,15 @@ func (m *Model) ScanList(structSlicePointer interface{}, bindToAttrName string, case 1: relationFields = relationAttrNameAndFields[0] } - return doScanList(m, result, structSlicePointer, bindToAttrName, relationAttrName, relationFields) + return doScanList(doScanListInput{ + Model: m, + Result: result, + StructSlicePointer: structSlicePointer, + StructSliceValue: out.SliceReflectValue, + BindToAttrName: bindToAttrName, + RelationAttrName: relationAttrName, + RelationFields: relationFields, + }) } // Count does "SELECT COUNT(x) FROM ..." statement for the model. diff --git a/database/gdb/gdb_type_result_scanlist.go b/database/gdb/gdb_type_result_scanlist.go index 95d0712caec..238f30bc7dc 100644 --- a/database/gdb/gdb_type_result_scanlist.go +++ b/database/gdb/gdb_type_result_scanlist.go @@ -85,6 +85,11 @@ import ( // // See the example or unit testing cases for clear understanding for this function. func (r Result) ScanList(structSlicePointer interface{}, bindToAttrName string, relationAttrNameAndFields ...string) (err error) { + out, err := checkGetSliceElementInfoForScanList(structSlicePointer, bindToAttrName) + if err != nil { + return err + } + var ( relationAttrName string relationFields string @@ -96,27 +101,32 @@ func (r Result) ScanList(structSlicePointer interface{}, bindToAttrName string, case 1: relationFields = relationAttrNameAndFields[0] } - return doScanList(nil, r, structSlicePointer, bindToAttrName, relationAttrName, relationFields) + return doScanList(doScanListInput{ + Model: nil, + Result: r, + StructSlicePointer: structSlicePointer, + StructSliceValue: out.SliceReflectValue, + BindToAttrName: bindToAttrName, + RelationAttrName: relationAttrName, + RelationFields: relationFields, + }) } -// doScanList converts `result` to struct slice which contains other complex struct attributes recursively. -// The parameter `model` is used for recursively scanning purpose, which means, it can scan the attribute struct/structs recursively, -// but it needs the Model for database accessing. -// Note that the parameter `structSlicePointer` should be type of *[]struct/*[]*struct. -func doScanList(model *Model, result Result, structSlicePointer interface{}, bindToAttrName, relationAttrName, relationFields string) (err error) { - if result.IsEmpty() { - return nil - } +type checkGetSliceElementInfoForScanListOutput struct { + SliceReflectValue reflect.Value + BindToAttrType reflect.Type +} + +func checkGetSliceElementInfoForScanList(structSlicePointer interface{}, bindToAttrName string) (out *checkGetSliceElementInfoForScanListOutput, err error) { // Necessary checks for parameters. - if bindToAttrName == "" { - return gerror.NewCode(gcode.CodeInvalidParameter, `bindToAttrName should not be empty`) + if structSlicePointer == nil { + return nil, gerror.NewCode(gcode.CodeInvalidParameter, `structSlicePointer cannot be nil`) } - - if relationAttrName == "." { - relationAttrName = "" + if bindToAttrName == "" { + return nil, gerror.NewCode(gcode.CodeInvalidParameter, `bindToAttrName should not be empty`) } - var ( + reflectType reflect.Type reflectValue = reflect.ValueOf(structSlicePointer) reflectKind = reflectValue.Kind() ) @@ -125,28 +135,84 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin reflectKind = reflectValue.Kind() } if reflectKind != reflect.Ptr { - return gerror.NewCodef( + return nil, gerror.NewCodef( gcode.CodeInvalidParameter, - "structSlicePointer should be type of *[]struct/*[]*struct, but got: %v", - reflectKind, + "structSlicePointer should be type of *[]struct/*[]*struct, but got: %s", + reflect.TypeOf(structSlicePointer).String(), ) } - reflectValue = reflectValue.Elem() - reflectKind = reflectValue.Kind() - if reflectKind != reflect.Slice && reflectKind != reflect.Array { - return gerror.NewCodef( + out = &checkGetSliceElementInfoForScanListOutput{ + SliceReflectValue: reflectValue.Elem(), + } + // Find the element struct type of the slice. + reflectType = reflectValue.Type().Elem().Elem() + reflectKind = reflectType.Kind() + for reflectKind == reflect.Ptr { + reflectType = reflectType.Elem() + reflectKind = reflectType.Kind() + } + if reflectKind != reflect.Struct { + err = gerror.NewCodef( gcode.CodeInvalidParameter, - "structSlicePointer should be type of *[]struct/*[]*struct, but got: %v", - reflectKind, + "structSlicePointer should be type of *[]struct/*[]*struct, but got: %s", + reflect.TypeOf(structSlicePointer).String(), ) + return } - length := len(result) + // Find the target field by given name. + structField, ok := reflectType.FieldByName(bindToAttrName) + if !ok { + return nil, gerror.NewCodef( + gcode.CodeInvalidParameter, + `field "%s" not found in element of "%s"`, + bindToAttrName, + reflect.TypeOf(structSlicePointer).String(), + ) + } + // Find the attribute struct type for ORM fields filtering. + reflectType = structField.Type + reflectKind = reflectType.Kind() + for reflectKind == reflect.Ptr { + reflectType = reflectType.Elem() + reflectKind = reflectType.Kind() + } + if reflectKind == reflect.Slice || reflectKind == reflect.Array { + reflectType = reflectType.Elem() + reflectKind = reflectType.Kind() + } + out.BindToAttrType = reflectType + return +} + +type doScanListInput struct { + Model *Model + Result Result + StructSlicePointer interface{} + StructSliceValue reflect.Value + BindToAttrName string + RelationAttrName string + RelationFields string +} + +// doScanList converts `result` to struct slice which contains other complex struct attributes recursively. +// The parameter `model` is used for recursively scanning purpose, which means, it can scan the attribute struct/structs recursively, +// but it needs the Model for database accessing. +// Note that the parameter `structSlicePointer` should be type of *[]struct/*[]*struct. +func doScanList(in doScanListInput) (err error) { + if in.Result.IsEmpty() { + return nil + } + if in.BindToAttrName == "" { + return gerror.NewCode(gcode.CodeInvalidParameter, `bindToAttrName should not be empty`) + } + + length := len(in.Result) if length == 0 { // The pointed slice is not empty. - if reflectValue.Len() > 0 { + if in.StructSliceValue.Len() > 0 { // It here checks if it has struct item, which is already initialized. // It then returns error to warn the developer its empty and no conversion. - if v := reflectValue.Index(0); v.Kind() != reflect.Ptr { + if v := in.StructSliceValue.Index(0); v.Kind() != reflect.Ptr { return sql.ErrNoRows } } @@ -156,10 +222,10 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin var ( arrayValue reflect.Value // Like: []*Entity arrayItemType reflect.Type // Like: *Entity - reflectType = reflect.TypeOf(structSlicePointer) + reflectType = reflect.TypeOf(in.StructSlicePointer) ) - if reflectValue.Len() > 0 { - arrayValue = reflectValue + if in.StructSliceValue.Len() > 0 { + arrayValue = in.StructSliceValue } else { arrayValue = reflect.MakeSlice(reflectType.Elem(), length, length) } @@ -173,17 +239,17 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin relationFromFieldName string // Eg: relationKV: id:uid -> id relationBindToFieldName string // Eg: relationKV: id:uid -> uid ) - if len(relationFields) > 0 { + if len(in.RelationFields) > 0 { // The relation key string of table filed name and attribute name // can be joined with char '=' or ':'. - array := gstr.SplitAndTrim(relationFields, "=") + array := gstr.SplitAndTrim(in.RelationFields, "=") if len(array) == 1 { // Compatible with old splitting char ':'. - array = gstr.SplitAndTrim(relationFields, ":") + array = gstr.SplitAndTrim(in.RelationFields, ":") } if len(array) == 1 { // The relation names are the same. - array = []string{relationFields, relationFields} + array = []string{in.RelationFields, in.RelationFields} } if len(array) == 2 { // Defined table field to relation attribute name. @@ -192,12 +258,12 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin // uid:UserId relationFromFieldName = array[0] relationBindToFieldName = array[1] - if key, _ := gutil.MapPossibleItemByKey(result[0].Map(), relationFromFieldName); key == "" { + if key, _ := gutil.MapPossibleItemByKey(in.Result[0].Map(), relationFromFieldName); key == "" { return gerror.NewCodef( gcode.CodeInvalidParameter, `cannot find possible related table field name "%s" from given relation fields "%s"`, relationFromFieldName, - relationFields, + in.RelationFields, ) } else { relationFromFieldName = key @@ -210,13 +276,13 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin } if relationFromFieldName != "" { // Note that the value might be type of slice. - relationDataMap = result.MapKeyValue(relationFromFieldName) + relationDataMap = in.Result.MapKeyValue(relationFromFieldName) } if len(relationDataMap) == 0 { return gerror.NewCodef( gcode.CodeInvalidParameter, `cannot find the relation data map, maybe invalid relation fields given "%v"`, - relationFields, + in.RelationFields, ) } } @@ -229,19 +295,19 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin bindToAttrField reflect.StructField ) if arrayItemType.Kind() == reflect.Ptr { - if bindToAttrField, ok = arrayItemType.Elem().FieldByName(bindToAttrName); !ok { + if bindToAttrField, ok = arrayItemType.Elem().FieldByName(in.BindToAttrName); !ok { return gerror.NewCodef( gcode.CodeInvalidParameter, `invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`, - bindToAttrName, + in.BindToAttrName, ) } } else { - if bindToAttrField, ok = arrayItemType.FieldByName(bindToAttrName); !ok { + if bindToAttrField, ok = arrayItemType.FieldByName(in.BindToAttrName); !ok { return gerror.NewCodef( gcode.CodeInvalidParameter, `invalid parameter bindToAttrName: cannot find attribute with name "%s" from slice element`, - bindToAttrName, + in.BindToAttrName, ) } } @@ -272,10 +338,10 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin } else { // Like: []Entity } - bindToAttrValue = arrayElemValue.FieldByName(bindToAttrName) - if relationAttrName != "" { + bindToAttrValue = arrayElemValue.FieldByName(in.BindToAttrName) + if in.RelationAttrName != "" { // Attribute value of current slice element. - relationFromAttrValue = arrayElemValue.FieldByName(relationAttrName) + relationFromAttrValue = arrayElemValue.FieldByName(in.RelationAttrName) if relationFromAttrValue.Kind() == reflect.Ptr { relationFromAttrValue = relationFromAttrValue.Elem() } @@ -284,10 +350,10 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin relationFromAttrValue = arrayElemValue } if len(relationDataMap) > 0 && !relationFromAttrValue.IsValid() { - return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, in.RelationFields) } // Check and find possible bind to attribute name. - if relationFields != "" && !relationBindToFieldNameChecked { + if in.RelationFields != "" && !relationBindToFieldNameChecked { relationFromAttrField = relationFromAttrValue.FieldByName(relationBindToFieldName) if !relationFromAttrField.IsValid() { filedMap, _ := structs.FieldMap(structs.FieldMapInput{ @@ -299,7 +365,7 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin gcode.CodeInvalidParameter, `cannot find possible related attribute name "%s" from given relation fields "%s"`, relationBindToFieldName, - relationFields, + in.RelationFields, ) } else { relationBindToFieldName = key @@ -320,20 +386,20 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin return err } // Recursively Scan. - if model != nil { - if err = model.doWithScanStructs(bindToAttrValue.Addr()); err != nil { + if in.Model != nil { + if err = in.Model.doWithScanStructs(bindToAttrValue.Addr()); err != nil { return nil } } } else { // Maybe the attribute does not exist yet. - return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, in.RelationFields) } } else { return gerror.NewCodef( gcode.CodeInvalidParameter, `relationKey should not be empty as field "%s" is slice`, - bindToAttrName, + in.BindToAttrName, ) } @@ -363,14 +429,14 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin } } else { // Maybe the attribute does not exist yet. - return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, in.RelationFields) } } else { - if i >= len(result) { + if i >= len(in.Result) { // There's no relational data. continue } - v := result[i] + v := in.Result[i] if v == nil { // There's no relational data. continue @@ -380,8 +446,8 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin } } // Recursively Scan. - if model != nil { - if err = model.doWithScanStruct(element); err != nil { + if in.Model != nil { + if err = in.Model.doWithScanStruct(element); err != nil { return err } } @@ -407,14 +473,14 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin } } else { // Maybe the attribute does not exist yet. - return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, relationFields) + return gerror.NewCodef(gcode.CodeInvalidParameter, `invalid relation fields specified: "%v"`, in.RelationFields) } } else { - if i >= len(result) { + if i >= len(in.Result) { // There's no relational data. continue } - relationDataItem := result[i] + relationDataItem := in.Result[i] if relationDataItem == nil { // There's no relational data. continue @@ -424,8 +490,8 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin } } // Recursively Scan. - if model != nil { - if err = model.doWithScanStruct(bindToAttrValue); err != nil { + if in.Model != nil { + if err = in.Model.doWithScanStruct(bindToAttrValue); err != nil { return err } } @@ -434,6 +500,6 @@ func doScanList(model *Model, result Result, structSlicePointer interface{}, bin return gerror.NewCodef(gcode.CodeInvalidParameter, `unsupported attribute type: %s`, bindToAttrKind.String()) } } - reflect.ValueOf(structSlicePointer).Elem().Set(arrayValue) + reflect.ValueOf(in.StructSlicePointer).Elem().Set(arrayValue) return nil } diff --git a/database/gdb/gdb_z_mysql_feature_scanlist_test.go b/database/gdb/gdb_z_mysql_feature_scanlist_test.go index a167e0a6d72..0388e2fa9af 100644 --- a/database/gdb/gdb_z_mysql_feature_scanlist_test.go +++ b/database/gdb/gdb_z_mysql_feature_scanlist_test.go @@ -477,6 +477,133 @@ CREATE TABLE %s ( }) } +func Test_Table_Relation_Many_ModelScanList(t *testing.T) { + var ( + tableUser = "user_" + gtime.TimestampMicroStr() + tableUserDetail = "user_detail_" + gtime.TimestampMicroStr() + tableUserScores = "user_scores_" + gtime.TimestampMicroStr() + ) + if _, err := db.Exec(ctx, fmt.Sprintf(` +CREATE TABLE %s ( + uid int(10) unsigned NOT NULL AUTO_INCREMENT, + name varchar(45) NOT NULL, + PRIMARY KEY (uid) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + `, tableUser)); err != nil { + gtest.Error(err) + } + defer dropTable(tableUser) + + if _, err := db.Exec(ctx, fmt.Sprintf(` +CREATE TABLE %s ( + uid int(10) unsigned NOT NULL AUTO_INCREMENT, + address varchar(45) NOT NULL, + PRIMARY KEY (uid) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + `, tableUserDetail)); err != nil { + gtest.Error(err) + } + defer dropTable(tableUserDetail) + + if _, err := db.Exec(ctx, fmt.Sprintf(` +CREATE TABLE %s ( + id int(10) unsigned NOT NULL AUTO_INCREMENT, + uid int(10) unsigned NOT NULL, + score int(10) unsigned NOT NULL, + PRIMARY KEY (id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + `, tableUserScores)); err != nil { + gtest.Error(err) + } + defer dropTable(tableUserScores) + + type EntityUser struct { + Uid int `json:"uid"` + Name string `json:"name"` + } + type EntityUserDetail struct { + Uid int `json:"uid"` + Address string `json:"address"` + } + type EntityUserScores struct { + Id int `json:"id"` + Uid int `json:"uid"` + Score int `json:"score"` + } + type Entity struct { + User *EntityUser + UserDetail *EntityUserDetail + UserScores []*EntityUserScores + } + + // Initialize the data. + gtest.C(t, func(t *gtest.T) { + var err error + for i := 1; i <= 5; i++ { + // User. + _, err = db.Insert(ctx, tableUser, g.Map{ + "uid": i, + "name": fmt.Sprintf(`name_%d`, i), + }) + t.AssertNil(err) + // Detail. + _, err = db.Insert(ctx, tableUserDetail, g.Map{ + "uid": i, + "address": fmt.Sprintf(`address_%d`, i), + }) + t.AssertNil(err) + // Scores. + for j := 1; j <= 5; j++ { + _, err = db.Insert(ctx, tableUserScores, g.Map{ + "uid": i, + "score": j, + }) + t.AssertNil(err) + } + } + }) + + //db.SetDebug(true) + // Result ScanList with struct elements and pointer attributes. + gtest.C(t, func(t *gtest.T) { + var users []Entity + // User + err := db.Model(tableUser). + Where("uid", g.Slice{3, 4}). + Order("uid asc"). + ScanList(&users, "User") + t.AssertNil(err) + t.AssertNil(err) + t.Assert(len(users), 2) + t.Assert(users[0].User, &EntityUser{3, "name_3"}) + t.Assert(users[1].User, &EntityUser{4, "name_4"}) + + // Detail + err = db.Model(tableUserDetail). + Where("uid", gdb.ListItemValues(users, "User", "Uid")). + Order("uid asc"). + ScanList(&users, "UserDetail", "User", "uid") + t.AssertNil(err) + t.Assert(users[0].UserDetail, &EntityUserDetail{3, "address_3"}) + t.Assert(users[1].UserDetail, &EntityUserDetail{4, "address_4"}) + + // Scores + err = db.Model(tableUserScores). + Where("uid", gdb.ListItemValues(users, "User", "Uid")). + Order("id asc"). + ScanList(&users, "UserScores", "User", "uid:Uid") + t.AssertNil(err) + t.Assert(len(users[0].UserScores), 5) + t.Assert(len(users[1].UserScores), 5) + t.Assert(users[0].UserScores[0].Uid, 3) + t.Assert(users[0].UserScores[0].Score, 1) + t.Assert(users[0].UserScores[4].Score, 5) + t.Assert(users[1].UserScores[0].Uid, 4) + t.Assert(users[1].UserScores[0].Score, 1) + t.Assert(users[1].UserScores[4].Score, 5) + }) +} + func Test_Table_Relation_Many_RelationKeyCaseInsensitive(t *testing.T) { var ( tableUser = "user_" + gtime.TimestampMicroStr() diff --git a/database/gdb/gdb_z_mysql_model_test.go b/database/gdb/gdb_z_mysql_model_test.go index 78397178031..a8f0db125f4 100644 --- a/database/gdb/gdb_z_mysql_model_test.go +++ b/database/gdb/gdb_z_mysql_model_test.go @@ -719,10 +719,19 @@ func Test_Model_Count(t *testing.T) { func Test_Model_Select(t *testing.T) { table := createInitTable() defer dropTable(table) + + type User struct { + Id int + Passport string + Password string + NickName string + CreateTime gtime.Time + } gtest.C(t, func(t *gtest.T) { - result, err := db.Model(table).All() + var users []User + err := db.Model(table).Scan(&users) t.AssertNil(err) - t.Assert(len(result), TableSize) + t.Assert(len(users), TableSize) }) } diff --git a/net/ghttp/ghttp_request_param.go b/net/ghttp/ghttp_request_param.go index 9d81c2196b0..c6c14697259 100644 --- a/net/ghttp/ghttp_request_param.go +++ b/net/ghttp/ghttp_request_param.go @@ -107,7 +107,7 @@ func (r *Request) doParse(pointer interface{}, requestType int) error { } } // Validation. - if err = gvalid.New().Data(pointer, data).Run(r.Context()); err != nil { + if err = gvalid.New().Data(pointer).Assoc(data).Run(r.Context()); err != nil { return err } @@ -126,7 +126,7 @@ func (r *Request) doParse(pointer interface{}, requestType int) error { for i := 0; i < reflectVal2.Len(); i++ { if err = gvalid.New(). - Data(reflectVal2.Index(i), j.Get(gconv.String(i)).Map()). + Data(reflectVal2.Index(i)).Assoc(j.Get(gconv.String(i)).Map()). Run(r.Context()); err != nil { return err } diff --git a/util/gvalid/gvalid_validator.go b/util/gvalid/gvalid_validator.go index 177d0633532..80ac39d9a34 100644 --- a/util/gvalid/gvalid_validator.go +++ b/util/gvalid/gvalid_validator.go @@ -105,26 +105,33 @@ func (v *Validator) Bail() *Validator { return newValidator } -// CaseInsensitive sets the mark for Case-Insensitive for those rules that need value comparison. -func (v *Validator) CaseInsensitive() *Validator { +// Ci sets the mark for Case-Insensitive for those rules that need value comparison. +func (v *Validator) Ci() *Validator { newValidator := v.Clone() newValidator.caseInsensitive = true return newValidator } // Data is a chaining operation function, which sets validation data for current operation. -// The optional parameter `assoc` is usually type of map, which specifies the parameter map used in union validation. -// Calling this function with `assoc` also sets `useDataInsteadOfObjectAttributes` true -func (v *Validator) Data(data interface{}, assoc ...interface{}) *Validator { +func (v *Validator) Data(data interface{}) *Validator { if data == nil { return v } newValidator := v.Clone() newValidator.data = data - if len(assoc) > 0 { - newValidator.assoc = assoc[0] - newValidator.useDataInsteadOfObjectAttributes = true + return newValidator +} + +// Assoc is a chaining operation function, which sets associated validation data for current operation. +// The optional parameter `assoc` is usually type of map, which specifies the parameter map used in union validation. +// Calling this function with `assoc` also sets `useDataInsteadOfObjectAttributes` true +func (v *Validator) Assoc(assoc interface{}) *Validator { + if assoc == nil { + return v } + newValidator := v.Clone() + newValidator.assoc = assoc + newValidator.useDataInsteadOfObjectAttributes = true return newValidator } diff --git a/util/gvalid/gvalid_validator_check_value.go b/util/gvalid/gvalid_validator_check_value.go index 4bdaad1e503..4635d50682c 100644 --- a/util/gvalid/gvalid_validator_check_value.go +++ b/util/gvalid/gvalid_validator_check_value.go @@ -550,7 +550,7 @@ func (v *Validator) doCheckValueRecursively(ctx context.Context, in doCheckValue validator := v.Clone() validator.rules = nil validator.messages = nil - if err := validator.Data(reflect.New(in.Type).Interface(), in.Value).Run(ctx); err != nil { + if err := validator.Data(reflect.New(in.Type).Interface()).Assoc(in.Value).Run(ctx); err != nil { // It merges the errors into single error map. for k, m := range err.(*validationError).errors { in.ErrorMaps[k] = m diff --git a/util/gvalid/gvalid_z_example_test.go b/util/gvalid/gvalid_z_example_test.go index 6de4e2e068d..1c52326b6f2 100644 --- a/util/gvalid/gvalid_z_example_test.go +++ b/util/gvalid/gvalid_z_example_test.go @@ -199,7 +199,7 @@ func ExampleValidator_Rules() { data := g.Map{ "password": "123", } - err := g.Validator().Data("", data). + err := g.Validator().Data("").Assoc(data). Rules("required-with:password"). Messages("请输入确认密码"). Run(gctx.New()) @@ -269,7 +269,7 @@ func ExampleValidator_CheckStruct() { if err := gconv.Scan(data, &user); err != nil { panic(err) } - err := g.Validator().Data(user, data).Run(gctx.New()) + err := g.Validator().Data(user).Assoc(data).Run(gctx.New()) if err != nil { fmt.Println(err.Items()) } @@ -442,6 +442,51 @@ func ExampleValidator_RequiredWithoutAll() { // The HusbandName field is required } +func ExampleValidator_Bail() { + type BizReq struct { + Account string `v:"bail|required|length:6,16|same:QQ"` + QQ string + Password string `v:"required|same:Password2"` + Password2 string `v:"required"` + } + var ( + ctx = context.Background() + req = BizReq{ + Account: "gf", + QQ: "123456", + Password: "goframe.org", + Password2: "goframe.org", + } + ) + if err := g.Validator().Data(req).Run(ctx); err != nil { + fmt.Println(err) + } + + // output: + // The Account value `gf` length must be between 6 and 16 +} + +func ExampleValidator_CaseInsensitive() { + type BizReq struct { + Account string `v:"required"` + Password string `v:"required|ci|same:Password2"` + Password2 string `v:"required"` + } + var ( + ctx = context.Background() + req = BizReq{ + Account: "gf", + Password: "Goframe.org", // Diff from Password2, but because of "ci", rule check passed + Password2: "goframe.org", + } + ) + if err := g.Validator().Data(req).Run(ctx); err != nil { + fmt.Println(err) + } + + // output: +} + func ExampleValidator_Date() { type BizReq struct { Date1 string `v:"date"` diff --git a/util/gvalid/gvalid_z_unit_feature_checkstruct_test.go b/util/gvalid/gvalid_z_unit_feature_checkstruct_test.go index d3c51d71c01..82b35f1abcd 100755 --- a/util/gvalid/gvalid_z_unit_feature_checkstruct_test.go +++ b/util/gvalid/gvalid_z_unit_feature_checkstruct_test.go @@ -414,10 +414,10 @@ func TestValidator_CheckStructWithData(t *testing.T) { Uid: 1, Nickname: "john", } - t.Assert(g.Validator().Data( - data, - g.Map{"uid": 1, "nickname": "john"}, - ).Run(context.TODO()), + t.Assert( + g.Validator().Data(data).Assoc( + g.Map{"uid": 1, "nickname": "john"}, + ).Run(context.TODO()), nil, ) }) @@ -427,7 +427,7 @@ func TestValidator_CheckStructWithData(t *testing.T) { Nickname string `v:"required-with:uid"` } data := UserApiSearch{} - t.AssertNE(g.Validator().Data(data, g.Map{}).Run(context.TODO()), nil) + t.AssertNE(g.Validator().Data(data).Assoc(g.Map{}).Run(context.TODO()), nil) }) gtest.C(t, func(t *gtest.T) { type UserApiSearch struct { @@ -437,7 +437,7 @@ func TestValidator_CheckStructWithData(t *testing.T) { data := UserApiSearch{ Uid: 1, } - t.AssertNE(g.Validator().Data(data, g.Map{}).Run(context.TODO()), nil) + t.AssertNE(g.Validator().Data(data).Assoc(g.Map{}).Run(context.TODO()), nil) }) gtest.C(t, func(t *gtest.T) { @@ -451,7 +451,7 @@ func TestValidator_CheckStructWithData(t *testing.T) { StartTime: nil, EndTime: nil, } - t.Assert(g.Validator().Data(data, g.Map{}).Run(context.TODO()), nil) + t.Assert(g.Validator().Data(data).Assoc(g.Map{}).Run(context.TODO()), nil) }) gtest.C(t, func(t *gtest.T) { type UserApiSearch struct { @@ -464,6 +464,6 @@ func TestValidator_CheckStructWithData(t *testing.T) { StartTime: gtime.Now(), EndTime: nil, } - t.AssertNE(g.Validator().Data(data, g.Map{"start_time": gtime.Now()}).Run(context.TODO()), nil) + t.AssertNE(g.Validator().Data(data).Assoc(g.Map{"start_time": gtime.Now()}).Run(context.TODO()), nil) }) } diff --git a/util/gvalid/gvalid_z_unit_feature_ci_test.go b/util/gvalid/gvalid_z_unit_feature_ci_test.go index 969603ce0e1..514fbb5e000 100644 --- a/util/gvalid/gvalid_z_unit_feature_ci_test.go +++ b/util/gvalid/gvalid_z_unit_feature_ci_test.go @@ -23,7 +23,7 @@ func Test_CI(t *testing.T) { t.AssertNil(err) }) gtest.C(t, func(t *gtest.T) { - err := g.Validator().CaseInsensitive().Rules("in:Id,Name").Data("id").Run(ctx) + err := g.Validator().Ci().Rules("in:Id,Name").Data("id").Run(ctx) t.AssertNil(err) }) } diff --git a/util/gvalid/gvalid_z_unit_feature_custom_rule_test.go b/util/gvalid/gvalid_z_unit_feature_custom_rule_test.go index af9110fa6b3..7172614040e 100644 --- a/util/gvalid/gvalid_z_unit_feature_custom_rule_test.go +++ b/util/gvalid/gvalid_z_unit_feature_custom_rule_test.go @@ -36,7 +36,7 @@ func Test_CustomRule1(t *testing.T) { gtest.C(t, func(t *gtest.T) { err := g.Validator().Data("123456").Rules(rule).Messages("custom message").Run(ctx) t.Assert(err.String(), "custom message") - err = g.Validator().Data("123456", g.Map{"data": "123456"}).Rules(rule).Messages("custom message").Run(ctx) + err = g.Validator().Data("123456").Assoc(g.Map{"data": "123456"}).Rules(rule).Messages("custom message").Run(ctx) t.Assert(err, nil) }) // Error with struct validation. @@ -176,7 +176,7 @@ func TestValidator_RuleFunc(t *testing.T) { err = g.Validator(). Rules(ruleName). Messages("custom message"). - Data("123456", g.Map{"data": "123456"}). + Data("123456").Assoc(g.Map{"data": "123456"}). RuleFunc(ruleName, ruleFunc). Run(ctx) t.AssertNil(err) @@ -232,7 +232,7 @@ func TestValidator_RuleFuncMap(t *testing.T) { err = g.Validator(). Rules(ruleName). Messages("custom message"). - Data("123456", g.Map{"data": "123456"}). + Data("123456").Assoc(g.Map{"data": "123456"}). RuleFuncMap(map[string]gvalid.RuleFunc{ ruleName: ruleFunc, }).Run(ctx) diff --git a/util/gvalid/gvalid_z_unit_feature_recursive_test.go b/util/gvalid/gvalid_z_unit_feature_recursive_test.go index dfa098254de..e71d3cf1b45 100755 --- a/util/gvalid/gvalid_z_unit_feature_recursive_test.go +++ b/util/gvalid/gvalid_z_unit_feature_recursive_test.go @@ -59,7 +59,7 @@ func Test_CheckStruct_Recursive_Struct_WithData(t *testing.T) { "Pass2": 200, }, } - err := g.Validator().Data(user, data).Run(ctx) + err := g.Validator().Data(user).Assoc(data).Run(ctx) t.AssertNE(err, nil) t.Assert(err.Maps()["Name"], nil) t.Assert(err.Maps()["Pass1"], g.Map{"same": "The Pass1 value `100` must be the same as field Pass2"}) diff --git a/util/gvalid/gvalid_z_unit_feature_rule_test.go b/util/gvalid/gvalid_z_unit_feature_rule_test.go index aea6e018b69..9aef7a93443 100755 --- a/util/gvalid/gvalid_z_unit_feature_rule_test.go +++ b/util/gvalid/gvalid_z_unit_feature_rule_test.go @@ -44,10 +44,10 @@ func Test_Required(t *testing.T) { if m := g.Validator().Data("").Rules("required").Messages(nil).Run(ctx); m == nil { t.Error(m) } - if m := g.Validator().Data("", map[string]interface{}{"id": 1, "age": 19}).Rules("required-if: id,1,age,18").Messages(nil).Run(ctx); m == nil { + if m := g.Validator().Data("").Assoc(map[string]interface{}{"id": 1, "age": 19}).Rules("required-if: id,1,age,18").Messages(nil).Run(ctx); m == nil { t.Error("Required校验失败") } - if m := g.Validator().Data("", map[string]interface{}{"id": 2, "age": 19}).Rules("required-if: id,1,age,18").Messages(nil).Run(ctx); m != nil { + if m := g.Validator().Data("").Assoc(map[string]interface{}{"id": 2, "age": 19}).Rules("required-if: id,1,age,18").Messages(nil).Run(ctx); m != nil { t.Error("Required校验失败") } } @@ -55,20 +55,20 @@ func Test_Required(t *testing.T) { func Test_RequiredIf(t *testing.T) { gtest.C(t, func(t *gtest.T) { rule := "required-if:id,1,age,18" - t.AssertNE(g.Validator().Data("", g.Map{"id": 1}).Rules(rule).Messages(nil).Run(ctx), nil) - t.Assert(g.Validator().Data("", g.Map{"id": 0}).Rules(rule).Messages(nil).Run(ctx), nil) - t.AssertNE(g.Validator().Data("", g.Map{"age": 18}).Rules(rule).Messages(nil).Run(ctx), nil) - t.Assert(g.Validator().Data("", g.Map{"age": 20}).Rules(rule).Messages(nil).Run(ctx), nil) + t.AssertNE(g.Validator().Data("").Assoc(g.Map{"id": 1}).Rules(rule).Messages(nil).Run(ctx), nil) + t.Assert(g.Validator().Data("").Assoc(g.Map{"id": 0}).Rules(rule).Messages(nil).Run(ctx), nil) + t.AssertNE(g.Validator().Data("").Assoc(g.Map{"age": 18}).Rules(rule).Messages(nil).Run(ctx), nil) + t.Assert(g.Validator().Data("").Assoc(g.Map{"age": 20}).Rules(rule).Messages(nil).Run(ctx), nil) }) } func Test_RequiredUnless(t *testing.T) { gtest.C(t, func(t *gtest.T) { rule := "required-unless:id,1,age,18" - t.Assert(g.Validator().Data("", g.Map{"id": 1}).Rules(rule).Messages(nil).Run(ctx), nil) - t.AssertNE(g.Validator().Data("", g.Map{"id": 0}).Rules(rule).Messages(nil).Run(ctx), nil) - t.Assert(g.Validator().Data("", g.Map{"age": 18}).Rules(rule).Messages(nil).Run(ctx), nil) - t.AssertNE(g.Validator().Data("", g.Map{"age": 20}).Rules(rule).Messages(nil).Run(ctx), nil) + t.Assert(g.Validator().Data("").Assoc(g.Map{"id": 1}).Rules(rule).Messages(nil).Run(ctx), nil) + t.AssertNE(g.Validator().Data("").Assoc(g.Map{"id": 0}).Rules(rule).Messages(nil).Run(ctx), nil) + t.Assert(g.Validator().Data("").Assoc(g.Map{"age": 18}).Rules(rule).Messages(nil).Run(ctx), nil) + t.AssertNE(g.Validator().Data("").Assoc(g.Map{"age": 20}).Rules(rule).Messages(nil).Run(ctx), nil) }) } @@ -86,9 +86,9 @@ func Test_RequiredWith(t *testing.T) { "id": 100, "name": "john", } - err1 := g.Validator().Data(val1, params1).Rules(rule).Messages(nil).Run(ctx) - err2 := g.Validator().Data(val1, params2).Rules(rule).Messages(nil).Run(ctx) - err3 := g.Validator().Data(val1, params3).Rules(rule).Messages(nil).Run(ctx) + err1 := g.Validator().Data(val1).Assoc(params1).Rules(rule).Messages(nil).Run(ctx) + err2 := g.Validator().Data(val1).Assoc(params2).Rules(rule).Messages(nil).Run(ctx) + err3 := g.Validator().Data(val1).Assoc(params3).Rules(rule).Messages(nil).Run(ctx) t.Assert(err1, nil) t.AssertNE(err2, nil) t.AssertNE(err3, nil) @@ -106,9 +106,9 @@ func Test_RequiredWith(t *testing.T) { params3 := g.Map{ "time": time.Time{}, } - err1 := g.Validator().Data(val1, params1).Rules(rule).Messages(nil).Run(ctx) - err2 := g.Validator().Data(val1, params2).Rules(rule).Messages(nil).Run(ctx) - err3 := g.Validator().Data(val1, params3).Rules(rule).Messages(nil).Run(ctx) + err1 := g.Validator().Data(val1).Assoc(params1).Rules(rule).Messages(nil).Run(ctx) + err2 := g.Validator().Data(val1).Assoc(params2).Rules(rule).Messages(nil).Run(ctx) + err3 := g.Validator().Data(val1).Assoc(params3).Rules(rule).Messages(nil).Run(ctx) t.Assert(err1, nil) t.AssertNE(err2, nil) t.Assert(err3, nil) @@ -125,9 +125,9 @@ func Test_RequiredWith(t *testing.T) { params3 := g.Map{ "time": time.Now(), } - err1 := g.Validator().Data(val1, params1).Rules(rule).Messages(nil).Run(ctx) - err2 := g.Validator().Data(val1, params2).Rules(rule).Messages(nil).Run(ctx) - err3 := g.Validator().Data(val1, params3).Rules(rule).Messages(nil).Run(ctx) + err1 := g.Validator().Data(val1).Assoc(params1).Rules(rule).Messages(nil).Run(ctx) + err2 := g.Validator().Data(val1).Assoc(params2).Rules(rule).Messages(nil).Run(ctx) + err3 := g.Validator().Data(val1).Assoc(params3).Rules(rule).Messages(nil).Run(ctx) t.Assert(err1, nil) t.AssertNE(err2, nil) t.AssertNE(err3, nil) @@ -175,9 +175,9 @@ func Test_RequiredWithAll(t *testing.T) { "id": 100, "name": "john", } - err1 := g.Validator().Data(val1, params1).Rules(rule).Messages(nil).Run(ctx) - err2 := g.Validator().Data(val1, params2).Rules(rule).Messages(nil).Run(ctx) - err3 := g.Validator().Data(val1, params3).Rules(rule).Messages(nil).Run(ctx) + err1 := g.Validator().Data(val1).Assoc(params1).Rules(rule).Messages(nil).Run(ctx) + err2 := g.Validator().Data(val1).Assoc(params2).Rules(rule).Messages(nil).Run(ctx) + err3 := g.Validator().Data(val1).Assoc(params3).Rules(rule).Messages(nil).Run(ctx) t.Assert(err1, nil) t.Assert(err2, nil) t.AssertNE(err3, nil) @@ -198,9 +198,9 @@ func Test_RequiredWithOut(t *testing.T) { "id": 100, "name": "john", } - err1 := g.Validator().Data(val1, params1).Rules(rule).Messages(nil).Run(ctx) - err2 := g.Validator().Data(val1, params2).Rules(rule).Messages(nil).Run(ctx) - err3 := g.Validator().Data(val1, params3).Rules(rule).Messages(nil).Run(ctx) + err1 := g.Validator().Data(val1).Assoc(params1).Rules(rule).Messages(nil).Run(ctx) + err2 := g.Validator().Data(val1).Assoc(params2).Rules(rule).Messages(nil).Run(ctx) + err3 := g.Validator().Data(val1).Assoc(params3).Rules(rule).Messages(nil).Run(ctx) t.AssertNE(err1, nil) t.AssertNE(err2, nil) t.Assert(err3, nil) @@ -221,9 +221,9 @@ func Test_RequiredWithOutAll(t *testing.T) { "id": 100, "name": "john", } - err1 := g.Validator().Data(val1, params1).Rules(rule).Messages(nil).Run(ctx) - err2 := g.Validator().Data(val1, params2).Rules(rule).Messages(nil).Run(ctx) - err3 := g.Validator().Data(val1, params3).Rules(rule).Messages(nil).Run(ctx) + err1 := g.Validator().Data(val1).Assoc(params1).Rules(rule).Messages(nil).Run(ctx) + err2 := g.Validator().Data(val1).Assoc(params2).Rules(rule).Messages(nil).Run(ctx) + err3 := g.Validator().Data(val1).Assoc(params3).Rules(rule).Messages(nil).Run(ctx) t.AssertNE(err1, nil) t.Assert(err2, nil) t.Assert(err3, nil) @@ -914,9 +914,9 @@ func Test_Same(t *testing.T) { "id": 100, "name": "john", } - err1 := g.Validator().Data(val1, params1).Rules(rule).Messages(nil).Run(ctx) - err2 := g.Validator().Data(val1, params2).Rules(rule).Messages(nil).Run(ctx) - err3 := g.Validator().Data(val1, params3).Rules(rule).Messages(nil).Run(ctx) + err1 := g.Validator().Data(val1).Assoc(params1).Rules(rule).Messages(nil).Run(ctx) + err2 := g.Validator().Data(val1).Assoc(params2).Rules(rule).Messages(nil).Run(ctx) + err3 := g.Validator().Data(val1).Assoc(params3).Rules(rule).Messages(nil).Run(ctx) t.AssertNE(err1, nil) t.Assert(err2, nil) t.Assert(err3, nil) @@ -937,9 +937,9 @@ func Test_Different(t *testing.T) { "id": 100, "name": "john", } - err1 := g.Validator().Data(val1, params1).Rules(rule).Messages(nil).Run(ctx) - err2 := g.Validator().Data(val1, params2).Rules(rule).Messages(nil).Run(ctx) - err3 := g.Validator().Data(val1, params3).Rules(rule).Messages(nil).Run(ctx) + err1 := g.Validator().Data(val1).Assoc(params1).Rules(rule).Messages(nil).Run(ctx) + err2 := g.Validator().Data(val1).Assoc(params2).Rules(rule).Messages(nil).Run(ctx) + err3 := g.Validator().Data(val1).Assoc(params3).Rules(rule).Messages(nil).Run(ctx) t.Assert(err1, nil) t.AssertNE(err2, nil) t.AssertNE(err3, nil)