diff --git a/cmd/gf/internal/cmd/cmd_z_unit_build_test.go b/cmd/gf/internal/cmd/cmd_z_unit_build_test.go index 33925969189..13c6f78db3b 100644 --- a/cmd/gf/internal/cmd/cmd_z_unit_build_test.go +++ b/cmd/gf/internal/cmd/cmd_z_unit_build_test.go @@ -104,7 +104,7 @@ func Test_Build_Single_VarMap(t *testing.T) { t.Assert(gfile.Exists(binaryPath), false) _, err = f.Index(ctx, cBuildInput{ - VarMap: map[string]interface{}{ + VarMap: map[string]any{ "a": "1", "b": "2", }, diff --git a/cmd/gf/internal/cmd/gendao/gendao_do.go b/cmd/gf/internal/cmd/gendao/gendao_do.go index 98afd6d7837..83683a58dfc 100644 --- a/cmd/gf/internal/cmd/gendao/gendao_do.go +++ b/cmd/gf/internal/cmd/gendao/gendao_do.go @@ -45,14 +45,14 @@ func generateDo(ctx context.Context, in CGenDaoInternalInput) { IsDo: true, }) ) - // replace all types to interface{}. + // replace all types to any. structDefinition, _ = gregex.ReplaceStringFuncMatch( "([A-Z]\\w*?)\\s+([\\w\\*\\.]+?)\\s+(//)", structDefinition, func(match []string) string { // If the type is already a pointer/slice/map, it does nothing. if !gstr.HasPrefix(match[2], "*") && !gstr.HasPrefix(match[2], "[]") && !gstr.HasPrefix(match[2], "map") { - return fmt.Sprintf(`%s interface{} %s`, match[1], match[3]) + return fmt.Sprintf(`%s any %s`, match[1], match[3]) } return match[0] }, diff --git a/cmd/gf/internal/cmd/genenums/genenums_parser.go b/cmd/gf/internal/cmd/genenums/genenums_parser.go index 21b9f96d98d..e0ab942ff75 100644 --- a/cmd/gf/internal/cmd/genenums/genenums_parser.go +++ b/cmd/gf/internal/cmd/genenums/genenums_parser.go @@ -113,12 +113,12 @@ func (p *EnumsParser) ParsePackage(pkg *packages.Package) { } func (p *EnumsParser) Export() string { - var typeEnumMap = make(map[string][]interface{}) + var typeEnumMap = make(map[string][]any) for _, enum := range p.enums { if typeEnumMap[enum.Type] == nil { - typeEnumMap[enum.Type] = make([]interface{}, 0) + typeEnumMap[enum.Type] = make([]any, 0) } - var value interface{} + var value any switch enum.Kind { case constant.Int: value = gconv.Int64(enum.Value) diff --git a/cmd/gf/internal/cmd/genpb/genpb_tag.go b/cmd/gf/internal/cmd/genpb/genpb_tag.go index 65a6c8ed790..b9b5c76bf92 100644 --- a/cmd/gf/internal/cmd/genpb/genpb_tag.go +++ b/cmd/gf/internal/cmd/genpb/genpb_tag.go @@ -109,7 +109,7 @@ func (c CGenPb) tagCommentIntoListMap(comment string, lineTagMap *gmap.ListMap) func (c CGenPb) listMapToStructTag(lineTagMap *gmap.ListMap) string { var tag string - lineTagMap.Iterator(func(key, value interface{}) bool { + lineTagMap.Iterator(func(key, value any) bool { if tag != "" { tag += " " } diff --git a/cmd/gf/internal/cmd/genservice/genservice_generate_template.go b/cmd/gf/internal/cmd/genservice/genservice_generate_template.go index 5947908d9ec..f753ddb7ba4 100644 --- a/cmd/gf/internal/cmd/genservice/genservice_generate_template.go +++ b/cmd/gf/internal/cmd/genservice/genservice_generate_template.go @@ -33,7 +33,7 @@ func (c CGenService) generateType(generatedContent *bytes.Buffer, srcStructFunct generatedContent.WriteString("type(") generatedContent.WriteString("\n") - srcStructFunctions.Iterator(func(key, value interface{}) bool { + srcStructFunctions.Iterator(func(key, value any) bool { var ( funcContents = make([]string, 0) funcContent string @@ -71,7 +71,7 @@ func (c CGenService) generateVar(generatedContent *bytes.Buffer, srcStructFuncti // Generating variable and register definitions. var variableContent string - srcStructFunctions.Iterator(func(key, value interface{}) bool { + srcStructFunctions.Iterator(func(key, value any) bool { structName := key.(string) variableContent += gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentVariable, g.MapStrStr{ "{StructName}": structName, @@ -93,7 +93,7 @@ func (c CGenService) generateVar(generatedContent *bytes.Buffer, srcStructFuncti // See: const.TemplateGenServiceContentRegister func (c CGenService) generateFunc(generatedContent *bytes.Buffer, srcStructFunctions *gmap.ListMap) { // Variable register function definitions. - srcStructFunctions.Iterator(func(key, value interface{}) bool { + srcStructFunctions.Iterator(func(key, value any) bool { structName := key.(string) generatedContent.WriteString(gstr.Trim(gstr.ReplaceByMap(consts.TemplateGenServiceContentRegister, g.MapStrStr{ "{StructName}": structName, diff --git a/cmd/gf/internal/cmd/testdata/gendao/generated_user/model/do/table_user.go b/cmd/gf/internal/cmd/testdata/gendao/generated_user/model/do/table_user.go index 656fb9c3db4..b2f78d7886b 100644 --- a/cmd/gf/internal/cmd/testdata/gendao/generated_user/model/do/table_user.go +++ b/cmd/gf/internal/cmd/testdata/gendao/generated_user/model/do/table_user.go @@ -12,11 +12,11 @@ import ( // TableUser is the golang structure of table table_user for DAO operations like Where/Data. type TableUser struct { g.Meta `orm:"table:table_user, do:true"` - Id interface{} // User ID - Passport interface{} // User Passport - Password interface{} // User Password - Nickname interface{} // User Nickname - Score interface{} // Total score amount. + Id any // User ID + Passport any // User Passport + Password any // User Password + Nickname any // User Nickname + Score any // Total score amount. CreateAt *gtime.Time // Created Time UpdateAt *gtime.Time // Updated Time } diff --git a/cmd/gf/internal/cmd/testdata/gendao/generated_user_field_mapping/model/do/table_user.go b/cmd/gf/internal/cmd/testdata/gendao/generated_user_field_mapping/model/do/table_user.go index 656fb9c3db4..b2f78d7886b 100644 --- a/cmd/gf/internal/cmd/testdata/gendao/generated_user_field_mapping/model/do/table_user.go +++ b/cmd/gf/internal/cmd/testdata/gendao/generated_user_field_mapping/model/do/table_user.go @@ -12,11 +12,11 @@ import ( // TableUser is the golang structure of table table_user for DAO operations like Where/Data. type TableUser struct { g.Meta `orm:"table:table_user, do:true"` - Id interface{} // User ID - Passport interface{} // User Passport - Password interface{} // User Password - Nickname interface{} // User Nickname - Score interface{} // Total score amount. + Id any // User ID + Passport any // User Passport + Password any // User Password + Nickname any // User Nickname + Score any // Total score amount. CreateAt *gtime.Time // Created Time UpdateAt *gtime.Time // Updated Time } diff --git a/cmd/gf/internal/cmd/testdata/gendao/generated_user_sqlite3/model/do/table_user.go b/cmd/gf/internal/cmd/testdata/gendao/generated_user_sqlite3/model/do/table_user.go index 75fcb5db1b7..36fbcb4b014 100644 --- a/cmd/gf/internal/cmd/testdata/gendao/generated_user_sqlite3/model/do/table_user.go +++ b/cmd/gf/internal/cmd/testdata/gendao/generated_user_sqlite3/model/do/table_user.go @@ -12,10 +12,10 @@ import ( // TableUser is the golang structure of table table_user for DAO operations like Where/Data. type TableUser struct { g.Meta `orm:"table:table_user, do:true"` - Id interface{} // - Passport interface{} // - Password interface{} // - Nickname interface{} // + Id any // + Passport any // + Password any // + Nickname any // CreatedAt *gtime.Time // UpdatedAt *gtime.Time // } diff --git a/cmd/gf/internal/cmd/testdata/gendao/generated_user_type_mapping/model/do/table_user.go b/cmd/gf/internal/cmd/testdata/gendao/generated_user_type_mapping/model/do/table_user.go index 656fb9c3db4..b2f78d7886b 100644 --- a/cmd/gf/internal/cmd/testdata/gendao/generated_user_type_mapping/model/do/table_user.go +++ b/cmd/gf/internal/cmd/testdata/gendao/generated_user_type_mapping/model/do/table_user.go @@ -12,11 +12,11 @@ import ( // TableUser is the golang structure of table table_user for DAO operations like Where/Data. type TableUser struct { g.Meta `orm:"table:table_user, do:true"` - Id interface{} // User ID - Passport interface{} // User Passport - Password interface{} // User Password - Nickname interface{} // User Nickname - Score interface{} // Total score amount. + Id any // User ID + Passport any // User Passport + Password any // User Password + Nickname any // User Nickname + Score any // Total score amount. CreateAt *gtime.Time // Created Time UpdateAt *gtime.Time // Updated Time } diff --git a/cmd/gf/internal/cmd/testdata/genservice/logic/article/article_extra.go b/cmd/gf/internal/cmd/testdata/genservice/logic/article/article_extra.go index 3d9c3d0fa22..2c207642dfd 100644 --- a/cmd/gf/internal/cmd/testdata/genservice/logic/article/article_extra.go +++ b/cmd/gf/internal/cmd/testdata/genservice/logic/article/article_extra.go @@ -63,14 +63,14 @@ func (s *sArticle) T3(ctx context.Context, b *gdbas.Model) (c, d *gdbas.Model, e * random comment */ -// func (s *sArticle) T4(i interface{}) interface{} +// func (s *sArticle) T4(i any) any // # $ % ^ & * ( ) _ + - = { } | [ ] \ : " ; ' < > ? , . / -func (s *sArticle) T4(i interface{}) interface{} { +func (s *sArticle) T4(i any) any { return nil } /** - * func (s *sArticle) T4(i interface{}) interface{} { + * func (s *sArticle) T4(i any) any { * return nil * } */ diff --git a/cmd/gf/internal/cmd/testdata/genservice/service/article.go b/cmd/gf/internal/cmd/testdata/genservice/service/article.go index 0d10924634e..6ad8269c9e0 100644 --- a/cmd/gf/internal/cmd/testdata/genservice/service/article.go +++ b/cmd/gf/internal/cmd/testdata/genservice/service/article.go @@ -36,9 +36,9 @@ type ( * @author oldme */ T3(ctx context.Context, b *gdbas.Model) (c *gdbas.Model, d *gdbas.Model, err error) - // func (s *sArticle) T4(i interface{}) interface{} + // func (s *sArticle) T4(i any) any // # $ % ^ & * ( ) _ + - = { } | [ ] \ : " ; ' < > ? , . / - T4(i interface{}) interface{} + T4(i any) any } ) diff --git a/cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_3.go b/cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_3.go index 14a1bf4e3d7..1f4e789f7de 100644 --- a/cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_3.go +++ b/cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_3.go @@ -12,11 +12,11 @@ import ( // User1 is the golang structure of table user1 for DAO operations like Where/Data. type User1 struct { g.Meta `orm:"table:user1, do:true"` - Id interface{} // User ID - Passport interface{} // User Passport - Password interface{} // User Password - Nickname interface{} // User Nickname - Score interface{} // Total score amount. + Id any // User ID + Passport any // User Passport + Password any // User Password + Nickname any // User Nickname + Score any // Total score amount. CreateAt *gtime.Time // Created Time UpdateAt *gtime.Time // Updated Time } diff --git a/cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_4.go b/cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_4.go index 8019772551f..25645fcff28 100644 --- a/cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_4.go +++ b/cmd/gf/internal/cmd/testdata/issue/2572/model/do/user_4.go @@ -12,11 +12,11 @@ import ( // User2 is the golang structure of table user2 for DAO operations like Where/Data. type User2 struct { g.Meta `orm:"table:user2, do:true"` - Id interface{} // User ID - Passport interface{} // User Passport - Password interface{} // User Password - Nickname interface{} // User Nickname - Score interface{} // Total score amount. + Id any // User ID + Passport any // User Passport + Password any // User Password + Nickname any // User Nickname + Score any // Total score amount. CreateAt *gtime.Time // Created Time UpdateAt *gtime.Time // Updated Time } diff --git a/cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_3.go b/cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_3.go index 14a1bf4e3d7..1f4e789f7de 100644 --- a/cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_3.go +++ b/cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_3.go @@ -12,11 +12,11 @@ import ( // User1 is the golang structure of table user1 for DAO operations like Where/Data. type User1 struct { g.Meta `orm:"table:user1, do:true"` - Id interface{} // User ID - Passport interface{} // User Passport - Password interface{} // User Password - Nickname interface{} // User Nickname - Score interface{} // Total score amount. + Id any // User ID + Passport any // User Passport + Password any // User Password + Nickname any // User Nickname + Score any // Total score amount. CreateAt *gtime.Time // Created Time UpdateAt *gtime.Time // Updated Time } diff --git a/cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_4.go b/cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_4.go index 8019772551f..25645fcff28 100644 --- a/cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_4.go +++ b/cmd/gf/internal/cmd/testdata/issue/2616/model/do/user_4.go @@ -12,11 +12,11 @@ import ( // User2 is the golang structure of table user2 for DAO operations like Where/Data. type User2 struct { g.Meta `orm:"table:user2, do:true"` - Id interface{} // User ID - Passport interface{} // User Passport - Password interface{} // User Password - Nickname interface{} // User Nickname - Score interface{} // Total score amount. + Id any // User ID + Passport any // User Passport + Password any // User Password + Nickname any // User Nickname + Score any // Total score amount. CreateAt *gtime.Time // Created Time UpdateAt *gtime.Time // Updated Time } diff --git a/cmd/gf/internal/cmd/testdata/issue/3749/model/do/table_user.go b/cmd/gf/internal/cmd/testdata/issue/3749/model/do/table_user.go index 6fe512a4401..7fed33dbc62 100644 --- a/cmd/gf/internal/cmd/testdata/issue/3749/model/do/table_user.go +++ b/cmd/gf/internal/cmd/testdata/issue/3749/model/do/table_user.go @@ -12,11 +12,11 @@ import ( // TableUser is the golang structure of table table_user for DAO operations like Where/Data. type TableUser struct { g.Meta `orm:"table:table_user, do:true"` - Id interface{} // User ID - ParentId interface{} // - Passport interface{} // User Passport - PassWord interface{} // User Password - Nickname2 interface{} // User Nickname + Id any // User ID + ParentId any // + Passport any // User Passport + PassWord any // User Password + Nickname2 any // User Nickname CreateAt *gtime.Time // Created Time UpdateAt *gtime.Time // Updated Time } diff --git a/cmd/gf/internal/utility/mlog/mlog.go b/cmd/gf/internal/utility/mlog/mlog.go index 7cbaa7699c7..21815011043 100644 --- a/cmd/gf/internal/utility/mlog/mlog.go +++ b/cmd/gf/internal/utility/mlog/mlog.go @@ -51,26 +51,26 @@ func SetHeaderPrint(enabled bool) { } } -func Print(v ...interface{}) { +func Print(v ...any) { logger.Print(ctx, v...) } -func Printf(format string, v ...interface{}) { +func Printf(format string, v ...any) { logger.Printf(ctx, format, v...) } -func Fatal(v ...interface{}) { +func Fatal(v ...any) { logger.Fatal(ctx, v...) } -func Fatalf(format string, v ...interface{}) { +func Fatalf(format string, v ...any) { logger.Fatalf(ctx, format, v...) } -func Debug(v ...interface{}) { +func Debug(v ...any) { logger.Debug(ctx, v...) } -func Debugf(format string, v ...interface{}) { +func Debugf(format string, v ...any) { logger.Debugf(ctx, format, v...) } diff --git a/container/garray/garray_normal_any.go b/container/garray/garray_normal_any.go index 0ce08bdaa54..cc17dcb3737 100644 --- a/container/garray/garray_normal_any.go +++ b/container/garray/garray_normal_any.go @@ -28,7 +28,7 @@ import ( // when its initialization and cannot be changed then. type Array struct { mu rwmutex.RWMutex - array []interface{} + array []any } // New creates and returns an empty array. @@ -49,7 +49,7 @@ func NewArray(safe ...bool) *Array { func NewArraySize(size int, cap int, safe ...bool) *Array { return &Array{ mu: rwmutex.Create(safe...), - array: make([]interface{}, size, cap), + array: make([]any, size, cap), } } @@ -59,7 +59,7 @@ func NewArrayRange(start, end, step int, safe ...bool) *Array { if step == 0 { panic(fmt.Sprintf(`invalid step value: %d`, step)) } - slice := make([]interface{}, 0) + slice := make([]any, 0) index := 0 for i := start; i <= end; i += step { slice = append(slice, i) @@ -70,20 +70,20 @@ func NewArrayRange(start, end, step int, safe ...bool) *Array { // NewFrom is alias of NewArrayFrom. // See NewArrayFrom. -func NewFrom(array []interface{}, safe ...bool) *Array { +func NewFrom(array []any, safe ...bool) *Array { return NewArrayFrom(array, safe...) } // NewFromCopy is alias of NewArrayFromCopy. // See NewArrayFromCopy. -func NewFromCopy(array []interface{}, safe ...bool) *Array { +func NewFromCopy(array []any, safe ...bool) *Array { return NewArrayFromCopy(array, safe...) } // NewArrayFrom creates and returns an array with given slice `array`. // The parameter `safe` is used to specify whether using array in concurrent-safety, // which is false in default. -func NewArrayFrom(array []interface{}, safe ...bool) *Array { +func NewArrayFrom(array []any, safe ...bool) *Array { return &Array{ mu: rwmutex.Create(safe...), array: array, @@ -93,8 +93,8 @@ func NewArrayFrom(array []interface{}, safe ...bool) *Array { // NewArrayFromCopy creates and returns an array from a copy of given slice `array`. // The parameter `safe` is used to specify whether using array in concurrent-safety, // which is false in default. -func NewArrayFromCopy(array []interface{}, safe ...bool) *Array { - newArray := make([]interface{}, len(array)) +func NewArrayFromCopy(array []any, safe ...bool) *Array { + newArray := make([]any, len(array)) copy(newArray, array) return &Array{ mu: rwmutex.Create(safe...), @@ -104,14 +104,14 @@ func NewArrayFromCopy(array []interface{}, safe ...bool) *Array { // At returns the value by the specified index. // If the given `index` is out of range of the array, it returns `nil`. -func (a *Array) At(index int) (value interface{}) { +func (a *Array) At(index int) (value any) { value, _ = a.Get(index) return } // Get returns the value by the specified index. // If the given `index` is out of range of the array, the `found` is false. -func (a *Array) Get(index int) (value interface{}, found bool) { +func (a *Array) Get(index int) (value any, found bool) { a.mu.RLock() defer a.mu.RUnlock() if index < 0 || index >= len(a.array) { @@ -121,7 +121,7 @@ func (a *Array) Get(index int) (value interface{}, found bool) { } // Set sets value to specified index. -func (a *Array) Set(index int, value interface{}) error { +func (a *Array) Set(index int, value any) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { @@ -132,7 +132,7 @@ func (a *Array) Set(index int, value interface{}) error { } // SetArray sets the underlying slice array with the given `array`. -func (a *Array) SetArray(array []interface{}) *Array { +func (a *Array) SetArray(array []any) *Array { a.mu.Lock() defer a.mu.Unlock() a.array = array @@ -140,7 +140,7 @@ func (a *Array) SetArray(array []interface{}) *Array { } // Replace replaces the array items by given `array` from the beginning of array. -func (a *Array) Replace(array []interface{}) *Array { +func (a *Array) Replace(array []any) *Array { a.mu.Lock() defer a.mu.Unlock() max := len(array) @@ -164,7 +164,7 @@ func (a *Array) Sum() (sum int) { } // SortFunc sorts the array by custom function `less`. -func (a *Array) SortFunc(less func(v1, v2 interface{}) bool) *Array { +func (a *Array) SortFunc(less func(v1, v2 any) bool) *Array { a.mu.Lock() defer a.mu.Unlock() sort.Slice(a.array, func(i, j int) bool { @@ -174,26 +174,26 @@ func (a *Array) SortFunc(less func(v1, v2 interface{}) bool) *Array { } // InsertBefore inserts the `values` to the front of `index`. -func (a *Array) InsertBefore(index int, values ...interface{}) error { +func (a *Array) InsertBefore(index int, values ...any) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } - rear := append([]interface{}{}, a.array[index:]...) + rear := append([]any{}, a.array[index:]...) a.array = append(a.array[0:index], values...) a.array = append(a.array, rear...) return nil } // InsertAfter inserts the `values` to the back of `index`. -func (a *Array) InsertAfter(index int, values ...interface{}) error { +func (a *Array) InsertAfter(index int, values ...any) error { a.mu.Lock() defer a.mu.Unlock() if index < 0 || index >= len(a.array) { return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array)) } - rear := append([]interface{}{}, a.array[index+1:]...) + rear := append([]any{}, a.array[index+1:]...) a.array = append(a.array[0:index+1], values...) a.array = append(a.array, rear...) return nil @@ -201,14 +201,14 @@ func (a *Array) InsertAfter(index int, values ...interface{}) error { // Remove removes an item by index. // If the given `index` is out of range of the array, the `found` is false. -func (a *Array) Remove(index int) (value interface{}, found bool) { +func (a *Array) Remove(index int) (value any, found bool) { a.mu.Lock() defer a.mu.Unlock() return a.doRemoveWithoutLock(index) } // doRemoveWithoutLock removes an item by index without lock. -func (a *Array) doRemoveWithoutLock(index int) (value interface{}, found bool) { +func (a *Array) doRemoveWithoutLock(index int) (value any, found bool) { if index < 0 || index >= len(a.array) { return nil, false } @@ -232,7 +232,7 @@ func (a *Array) doRemoveWithoutLock(index int) (value interface{}, found bool) { // RemoveValue removes an item by value. // It returns true if value is found in the array, or else false if not found. -func (a *Array) RemoveValue(value interface{}) bool { +func (a *Array) RemoveValue(value any) bool { a.mu.Lock() defer a.mu.Unlock() if i := a.doSearchWithoutLock(value); i != -1 { @@ -243,7 +243,7 @@ func (a *Array) RemoveValue(value interface{}) bool { } // RemoveValues removes multiple items by `values`. -func (a *Array) RemoveValues(values ...interface{}) { +func (a *Array) RemoveValues(values ...any) { a.mu.Lock() defer a.mu.Unlock() for _, value := range values { @@ -254,7 +254,7 @@ func (a *Array) RemoveValues(values ...interface{}) { } // PushLeft pushes one or multiple items to the beginning of array. -func (a *Array) PushLeft(value ...interface{}) *Array { +func (a *Array) PushLeft(value ...any) *Array { a.mu.Lock() a.array = append(value, a.array...) a.mu.Unlock() @@ -263,7 +263,7 @@ func (a *Array) PushLeft(value ...interface{}) *Array { // PushRight pushes one or multiple items to the end of array. // It equals to Append. -func (a *Array) PushRight(value ...interface{}) *Array { +func (a *Array) PushRight(value ...any) *Array { a.mu.Lock() a.array = append(a.array, value...) a.mu.Unlock() @@ -272,14 +272,14 @@ func (a *Array) PushRight(value ...interface{}) *Array { // PopRand randomly pops and return an item out of array. // Note that if the array is empty, the `found` is false. -func (a *Array) PopRand() (value interface{}, found bool) { +func (a *Array) PopRand() (value any, found bool) { a.mu.Lock() defer a.mu.Unlock() return a.doRemoveWithoutLock(grand.Intn(len(a.array))) } // PopRands randomly pops and returns `size` items out of array. -func (a *Array) PopRands(size int) []interface{} { +func (a *Array) PopRands(size int) []any { a.mu.Lock() defer a.mu.Unlock() if size <= 0 || len(a.array) == 0 { @@ -288,7 +288,7 @@ func (a *Array) PopRands(size int) []interface{} { if size >= len(a.array) { size = len(a.array) } - array := make([]interface{}, size) + array := make([]any, size) for i := 0; i < size; i++ { array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array))) } @@ -297,7 +297,7 @@ func (a *Array) PopRands(size int) []interface{} { // PopLeft pops and returns an item from the beginning of array. // Note that if the array is empty, the `found` is false. -func (a *Array) PopLeft() (value interface{}, found bool) { +func (a *Array) PopLeft() (value any, found bool) { a.mu.Lock() defer a.mu.Unlock() if len(a.array) == 0 { @@ -310,7 +310,7 @@ func (a *Array) PopLeft() (value interface{}, found bool) { // PopRight pops and returns an item from the end of array. // Note that if the array is empty, the `found` is false. -func (a *Array) PopRight() (value interface{}, found bool) { +func (a *Array) PopRight() (value any, found bool) { a.mu.Lock() defer a.mu.Unlock() index := len(a.array) - 1 @@ -323,7 +323,7 @@ func (a *Array) PopRight() (value interface{}, found bool) { } // PopLefts pops and returns `size` items from the beginning of array. -func (a *Array) PopLefts(size int) []interface{} { +func (a *Array) PopLefts(size int) []any { a.mu.Lock() defer a.mu.Unlock() if size <= 0 || len(a.array) == 0 { @@ -340,7 +340,7 @@ func (a *Array) PopLefts(size int) []interface{} { } // PopRights pops and returns `size` items from the end of array. -func (a *Array) PopRights(size int) []interface{} { +func (a *Array) PopRights(size int) []any { a.mu.Lock() defer a.mu.Unlock() if size <= 0 || len(a.array) == 0 { @@ -364,7 +364,7 @@ func (a *Array) PopRights(size int) []interface{} { // If `end` is negative, then the offset will start from the end of array. // If `end` is omitted, then the sequence will have everything from start up // until the end of the array. -func (a *Array) Range(start int, end ...int) []interface{} { +func (a *Array) Range(start int, end ...int) []any { a.mu.RLock() defer a.mu.RUnlock() offsetEnd := len(a.array) @@ -377,9 +377,9 @@ func (a *Array) Range(start int, end ...int) []interface{} { if start < 0 { start = 0 } - array := ([]interface{})(nil) + array := ([]any)(nil) if a.mu.IsSafe() { - array = make([]interface{}, offsetEnd-start) + array = make([]any, offsetEnd-start) copy(array, a.array[start:offsetEnd]) } else { array = a.array[start:offsetEnd] @@ -400,7 +400,7 @@ func (a *Array) Range(start int, end ...int) []interface{} { // If it is omitted, then the sequence will have everything from offset up until the end of the array. // // Any possibility crossing the left border of array, it will fail. -func (a *Array) SubSlice(offset int, length ...int) []interface{} { +func (a *Array) SubSlice(offset int, length ...int) []any { a.mu.RLock() defer a.mu.RUnlock() size := len(a.array) @@ -429,7 +429,7 @@ func (a *Array) SubSlice(offset int, length ...int) []interface{} { size = len(a.array) - offset } if a.mu.IsSafe() { - s := make([]interface{}, size) + s := make([]any, size) copy(s, a.array[offset:]) return s } else { @@ -438,7 +438,7 @@ func (a *Array) SubSlice(offset int, length ...int) []interface{} { } // Append is alias of PushRight, please See PushRight. -func (a *Array) Append(value ...interface{}) *Array { +func (a *Array) Append(value ...any) *Array { a.PushRight(value...) return a } @@ -454,11 +454,11 @@ func (a *Array) Len() int { // Slice returns the underlying data of array. // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // or else a pointer to the underlying data. -func (a *Array) Slice() []interface{} { +func (a *Array) Slice() []any { if a.mu.IsSafe() { a.mu.RLock() defer a.mu.RUnlock() - array := make([]interface{}, len(a.array)) + array := make([]any, len(a.array)) copy(array, a.array) return array } else { @@ -466,15 +466,15 @@ func (a *Array) Slice() []interface{} { } } -// Interfaces returns current array as []interface{}. -func (a *Array) Interfaces() []interface{} { +// Interfaces returns current array as []any. +func (a *Array) Interfaces() []any { return a.Slice() } // Clone returns a new array, which is a copy of current array. func (a *Array) Clone() (newArray *Array) { a.mu.RLock() - array := make([]interface{}, len(a.array)) + array := make([]any, len(a.array)) copy(array, a.array) a.mu.RUnlock() return NewArrayFrom(array, a.mu.IsSafe()) @@ -484,26 +484,26 @@ func (a *Array) Clone() (newArray *Array) { func (a *Array) Clear() *Array { a.mu.Lock() if len(a.array) > 0 { - a.array = make([]interface{}, 0) + a.array = make([]any, 0) } a.mu.Unlock() return a } // Contains checks whether a value exists in the array. -func (a *Array) Contains(value interface{}) bool { +func (a *Array) Contains(value any) bool { return a.Search(value) != -1 } // Search searches array by `value`, returns the index of `value`, // or returns -1 if not exists. -func (a *Array) Search(value interface{}) int { +func (a *Array) Search(value any) int { a.mu.RLock() defer a.mu.RUnlock() return a.doSearchWithoutLock(value) } -func (a *Array) doSearchWithoutLock(value interface{}) int { +func (a *Array) doSearchWithoutLock(value any) int { if len(a.array) == 0 { return -1 } @@ -527,9 +527,9 @@ func (a *Array) Unique() *Array { } var ( ok bool - temp interface{} - uniqueSet = make(map[interface{}]struct{}) - uniqueArray = make([]interface{}, 0, len(a.array)) + temp any + uniqueSet = make(map[any]struct{}) + uniqueArray = make([]any, 0, len(a.array)) ) for i := 0; i < len(a.array); i++ { temp = a.array[i] @@ -544,7 +544,7 @@ func (a *Array) Unique() *Array { } // LockFunc locks writing by callback function `f`. -func (a *Array) LockFunc(f func(array []interface{})) *Array { +func (a *Array) LockFunc(f func(array []any)) *Array { a.mu.Lock() defer a.mu.Unlock() f(a.array) @@ -552,7 +552,7 @@ func (a *Array) LockFunc(f func(array []interface{})) *Array { } // RLockFunc locks reading by callback function `f`. -func (a *Array) RLockFunc(f func(array []interface{})) *Array { +func (a *Array) RLockFunc(f func(array []any)) *Array { a.mu.RLock() defer a.mu.RUnlock() f(a.array) @@ -563,13 +563,13 @@ func (a *Array) RLockFunc(f func(array []interface{})) *Array { // The parameter `array` can be any garray or slice type. // The difference between Merge and Append is Append supports only specified slice type, // but Merge supports more parameter types. -func (a *Array) Merge(array interface{}) *Array { +func (a *Array) Merge(array any) *Array { return a.Append(gconv.Interfaces(array)...) } // Fill fills an array with num entries of the value `value`, // keys starting at the `startIndex` parameter. -func (a *Array) Fill(startIndex int, num int, value interface{}) error { +func (a *Array) Fill(startIndex int, num int, value any) error { a.mu.Lock() defer a.mu.Unlock() if startIndex < 0 || startIndex > len(a.array) { @@ -588,7 +588,7 @@ func (a *Array) Fill(startIndex int, num int, value interface{}) error { // Chunk splits an array into multiple arrays, // the size of each array is determined by `size`. // The last chunk may contain less than size elements. -func (a *Array) Chunk(size int) [][]interface{} { +func (a *Array) Chunk(size int) [][]any { if size < 1 { return nil } @@ -596,7 +596,7 @@ func (a *Array) Chunk(size int) [][]interface{} { defer a.mu.RUnlock() length := len(a.array) chunks := int(math.Ceil(float64(length) / float64(size))) - var n [][]interface{} + var n [][]any for i, end := 0, 0; chunks > 0; chunks-- { end = (i + 1) * size if end > length { @@ -612,7 +612,7 @@ func (a *Array) Chunk(size int) [][]interface{} { // If size is positive then the array is padded on the right, or negative on the left. // If the absolute value of `size` is less than or equal to the length of the array // then no padding takes place. -func (a *Array) Pad(size int, val interface{}) *Array { +func (a *Array) Pad(size int, val any) *Array { a.mu.Lock() defer a.mu.Unlock() if size == 0 || (size > 0 && size < len(a.array)) || (size < 0 && size > -len(a.array)) { @@ -623,7 +623,7 @@ func (a *Array) Pad(size int, val interface{}) *Array { n = -size } n -= len(a.array) - tmp := make([]interface{}, n) + tmp := make([]any, n) for i := 0; i < n; i++ { tmp[i] = val } @@ -636,7 +636,7 @@ func (a *Array) Pad(size int, val interface{}) *Array { } // Rand randomly returns one item from array(no deleting). -func (a *Array) Rand() (value interface{}, found bool) { +func (a *Array) Rand() (value any, found bool) { a.mu.RLock() defer a.mu.RUnlock() if len(a.array) == 0 { @@ -646,13 +646,13 @@ func (a *Array) Rand() (value interface{}, found bool) { } // Rands randomly returns `size` items from array(no deleting). -func (a *Array) Rands(size int) []interface{} { +func (a *Array) Rands(size int) []any { a.mu.RLock() defer a.mu.RUnlock() if size <= 0 || len(a.array) == 0 { return nil } - array := make([]interface{}, size) + array := make([]any, size) for i := 0; i < size; i++ { array[i] = a.array[grand.Intn(len(a.array))] } @@ -697,8 +697,8 @@ func (a *Array) Join(glue string) string { } // CountValues counts the number of occurrences of all values in the array. -func (a *Array) CountValues() map[interface{}]int { - m := make(map[interface{}]int) +func (a *Array) CountValues() map[any]int { + m := make(map[any]int) a.mu.RLock() defer a.mu.RUnlock() for _, v := range a.array { @@ -708,13 +708,13 @@ func (a *Array) CountValues() map[interface{}]int { } // Iterator is alias of IteratorAsc. -func (a *Array) Iterator(f func(k int, v interface{}) bool) { +func (a *Array) Iterator(f func(k int, v any) bool) { a.IteratorAsc(f) } // IteratorAsc iterates the array readonly in ascending order with given callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. -func (a *Array) IteratorAsc(f func(k int, v interface{}) bool) { +func (a *Array) IteratorAsc(f func(k int, v any) bool) { a.mu.RLock() defer a.mu.RUnlock() for k, v := range a.array { @@ -726,7 +726,7 @@ func (a *Array) IteratorAsc(f func(k int, v interface{}) bool) { // IteratorDesc iterates the array readonly in descending order with given callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. -func (a *Array) IteratorDesc(f func(k int, v interface{}) bool) { +func (a *Array) IteratorDesc(f func(k int, v any) bool) { a.mu.RLock() defer a.mu.RUnlock() for i := len(a.array) - 1; i >= 0; i-- { @@ -772,7 +772,7 @@ func (a Array) MarshalJSON() ([]byte, error) { // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (a *Array) UnmarshalJSON(b []byte) error { if a.array == nil { - a.array = make([]interface{}, 0) + a.array = make([]any, 0) } a.mu.Lock() defer a.mu.Unlock() @@ -783,7 +783,7 @@ func (a *Array) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for array. -func (a *Array) UnmarshalValue(value interface{}) error { +func (a *Array) UnmarshalValue(value any) error { a.mu.Lock() defer a.mu.Unlock() switch value.(type) { @@ -798,7 +798,7 @@ func (a *Array) UnmarshalValue(value interface{}) error { // Filter iterates array and filters elements using custom callback function. // It removes the element from array if callback function `filter` returns true, // it or else does nothing and continues iterating. -func (a *Array) Filter(filter func(index int, value interface{}) bool) *Array { +func (a *Array) Filter(filter func(index int, value any) bool) *Array { a.mu.Lock() defer a.mu.Unlock() for i := 0; i < len(a.array); { @@ -841,7 +841,7 @@ func (a *Array) FilterEmpty() *Array { } // Walk applies a user supplied function `f` to every item of array. -func (a *Array) Walk(f func(value interface{}) interface{}) *Array { +func (a *Array) Walk(f func(value any) any) *Array { a.mu.Lock() defer a.mu.Unlock() for i, v := range a.array { @@ -856,13 +856,13 @@ func (a *Array) IsEmpty() bool { } // DeepCopy implements interface for deep copy of current type. -func (a *Array) DeepCopy() interface{} { +func (a *Array) DeepCopy() any { if a == nil { return nil } a.mu.RLock() defer a.mu.RUnlock() - newSlice := make([]interface{}, len(a.array)) + newSlice := make([]any, len(a.array)) for i, v := range a.array { newSlice[i] = deepcopy.Copy(v) } diff --git a/container/garray/garray_normal_int.go b/container/garray/garray_normal_int.go index 16e59a71c94..87526a9f220 100644 --- a/container/garray/garray_normal_int.go +++ b/container/garray/garray_normal_int.go @@ -478,11 +478,11 @@ func (a *IntArray) Slice() []int { return array } -// Interfaces returns current array as []interface{}. -func (a *IntArray) Interfaces() []interface{} { +// Interfaces returns current array as []any. +func (a *IntArray) Interfaces() []any { a.mu.RLock() defer a.mu.RUnlock() - array := make([]interface{}, len(a.array)) + array := make([]any, len(a.array)) for k, v := range a.array { array[k] = v } @@ -581,7 +581,7 @@ func (a *IntArray) RLockFunc(f func(array []int)) *IntArray { // The parameter `array` can be any garray or slice type. // The difference between Merge and Append is Append supports only specified slice type, // but Merge supports more parameter types. -func (a *IntArray) Merge(array interface{}) *IntArray { +func (a *IntArray) Merge(array any) *IntArray { return a.Append(gconv.Ints(array)...) } @@ -788,7 +788,7 @@ func (a *IntArray) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for array. -func (a *IntArray) UnmarshalValue(value interface{}) error { +func (a *IntArray) UnmarshalValue(value any) error { a.mu.Lock() defer a.mu.Unlock() switch value.(type) { @@ -846,7 +846,7 @@ func (a *IntArray) IsEmpty() bool { } // DeepCopy implements interface for deep copy of current type. -func (a *IntArray) DeepCopy() interface{} { +func (a *IntArray) DeepCopy() any { if a == nil { return nil } diff --git a/container/garray/garray_normal_str.go b/container/garray/garray_normal_str.go index 55921596328..06b61c3a31b 100644 --- a/container/garray/garray_normal_str.go +++ b/container/garray/garray_normal_str.go @@ -454,11 +454,11 @@ func (a *StrArray) Slice() []string { return array } -// Interfaces returns current array as []interface{}. -func (a *StrArray) Interfaces() []interface{} { +// Interfaces returns current array as []any. +func (a *StrArray) Interfaces() []any { a.mu.RLock() defer a.mu.RUnlock() - array := make([]interface{}, len(a.array)) + array := make([]any, len(a.array)) for k, v := range a.array { array[k] = v } @@ -573,7 +573,7 @@ func (a *StrArray) RLockFunc(f func(array []string)) *StrArray { // The parameter `array` can be any garray or slice type. // The difference between Merge and Append is Append supports only specified slice type, // but Merge supports more parameter types. -func (a *StrArray) Merge(array interface{}) *StrArray { +func (a *StrArray) Merge(array any) *StrArray { return a.Append(gconv.Strings(array)...) } @@ -787,7 +787,7 @@ func (a *StrArray) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for array. -func (a *StrArray) UnmarshalValue(value interface{}) error { +func (a *StrArray) UnmarshalValue(value any) error { a.mu.Lock() defer a.mu.Unlock() switch value.(type) { @@ -845,7 +845,7 @@ func (a *StrArray) IsEmpty() bool { } // DeepCopy implements interface for deep copy of current type. -func (a *StrArray) DeepCopy() interface{} { +func (a *StrArray) DeepCopy() any { if a == nil { return nil } diff --git a/container/garray/garray_sorted_any.go b/container/garray/garray_sorted_any.go index 8ab6e3ee539..d2f0a0a7241 100644 --- a/container/garray/garray_sorted_any.go +++ b/container/garray/garray_sorted_any.go @@ -29,9 +29,9 @@ import ( // when its initialization and cannot be changed then. type SortedArray struct { mu rwmutex.RWMutex - array []interface{} - unique bool // Whether enable unique feature(false) - comparator func(a, b interface{}) int // Comparison function(it returns -1: a < b; 0: a == b; 1: a > b) + array []any + unique bool // Whether enable unique feature(false) + comparator func(a, b any) int // Comparison function(it returns -1: a < b; 0: a == b; 1: a > b) } // NewSortedArray creates and returns an empty sorted array. @@ -40,28 +40,28 @@ type SortedArray struct { // if it returns value < 0, means `a` < `b`; the `a` will be inserted before `b`; // if it returns value = 0, means `a` = `b`; the `a` will be replaced by `b`; // if it returns value > 0, means `a` > `b`; the `a` will be inserted after `b`; -func NewSortedArray(comparator func(a, b interface{}) int, safe ...bool) *SortedArray { +func NewSortedArray(comparator func(a, b any) int, safe ...bool) *SortedArray { return NewSortedArraySize(0, comparator, safe...) } // NewSortedArraySize create and returns an sorted array with given size and cap. // The parameter `safe` is used to specify whether using array in concurrent-safety, // which is false in default. -func NewSortedArraySize(cap int, comparator func(a, b interface{}) int, safe ...bool) *SortedArray { +func NewSortedArraySize(cap int, comparator func(a, b any) int, safe ...bool) *SortedArray { return &SortedArray{ mu: rwmutex.Create(safe...), - array: make([]interface{}, 0, cap), + array: make([]any, 0, cap), comparator: comparator, } } // NewSortedArrayRange creates and returns an array by a range from `start` to `end` // with step value `step`. -func NewSortedArrayRange(start, end, step int, comparator func(a, b interface{}) int, safe ...bool) *SortedArray { +func NewSortedArrayRange(start, end, step int, comparator func(a, b any) int, safe ...bool) *SortedArray { if step == 0 { panic(fmt.Sprintf(`invalid step value: %d`, step)) } - slice := make([]interface{}, 0) + slice := make([]any, 0) index := 0 for i := start; i <= end; i += step { slice = append(slice, i) @@ -73,7 +73,7 @@ func NewSortedArrayRange(start, end, step int, comparator func(a, b interface{}) // NewSortedArrayFrom creates and returns an sorted array with given slice `array`. // The parameter `safe` is used to specify whether using array in concurrent-safety, // which is false in default. -func NewSortedArrayFrom(array []interface{}, comparator func(a, b interface{}) int, safe ...bool) *SortedArray { +func NewSortedArrayFrom(array []any, comparator func(a, b any) int, safe ...bool) *SortedArray { a := NewSortedArraySize(0, comparator, safe...) a.array = array sort.Slice(a.array, func(i, j int) bool { @@ -85,21 +85,21 @@ func NewSortedArrayFrom(array []interface{}, comparator func(a, b interface{}) i // NewSortedArrayFromCopy creates and returns an sorted array from a copy of given slice `array`. // The parameter `safe` is used to specify whether using array in concurrent-safety, // which is false in default. -func NewSortedArrayFromCopy(array []interface{}, comparator func(a, b interface{}) int, safe ...bool) *SortedArray { - newArray := make([]interface{}, len(array)) +func NewSortedArrayFromCopy(array []any, comparator func(a, b any) int, safe ...bool) *SortedArray { + newArray := make([]any, len(array)) copy(newArray, array) return NewSortedArrayFrom(newArray, comparator, safe...) } // At returns the value by the specified index. // If the given `index` is out of range of the array, it returns `nil`. -func (a *SortedArray) At(index int) (value interface{}) { +func (a *SortedArray) At(index int) (value any) { value, _ = a.Get(index) return } // SetArray sets the underlying slice array with the given `array`. -func (a *SortedArray) SetArray(array []interface{}) *SortedArray { +func (a *SortedArray) SetArray(array []any) *SortedArray { a.mu.Lock() defer a.mu.Unlock() a.array = array @@ -111,7 +111,7 @@ func (a *SortedArray) SetArray(array []interface{}) *SortedArray { // SetComparator sets/changes the comparator for sorting. // It resorts the array as the comparator is changed. -func (a *SortedArray) SetComparator(comparator func(a, b interface{}) int) { +func (a *SortedArray) SetComparator(comparator func(a, b any) int) { a.mu.Lock() defer a.mu.Unlock() a.comparator = comparator @@ -134,12 +134,12 @@ func (a *SortedArray) Sort() *SortedArray { // Add adds one or multiple values to sorted array, the array always keeps sorted. // It's alias of function Append, see Append. -func (a *SortedArray) Add(values ...interface{}) *SortedArray { +func (a *SortedArray) Add(values ...any) *SortedArray { return a.Append(values...) } // Append adds one or multiple values to sorted array, the array always keeps sorted. -func (a *SortedArray) Append(values ...interface{}) *SortedArray { +func (a *SortedArray) Append(values ...any) *SortedArray { if len(values) == 0 { return a } @@ -157,14 +157,14 @@ func (a *SortedArray) Append(values ...interface{}) *SortedArray { if cmp > 0 { index++ } - a.array = append(a.array[:index], append([]interface{}{value}, a.array[index:]...)...) + a.array = append(a.array[:index], append([]any{value}, a.array[index:]...)...) } return a } // Get returns the value by the specified index. // If the given `index` is out of range of the array, the `found` is false. -func (a *SortedArray) Get(index int) (value interface{}, found bool) { +func (a *SortedArray) Get(index int) (value any, found bool) { a.mu.RLock() defer a.mu.RUnlock() if index < 0 || index >= len(a.array) { @@ -175,14 +175,14 @@ func (a *SortedArray) Get(index int) (value interface{}, found bool) { // Remove removes an item by index. // If the given `index` is out of range of the array, the `found` is false. -func (a *SortedArray) Remove(index int) (value interface{}, found bool) { +func (a *SortedArray) Remove(index int) (value any, found bool) { a.mu.Lock() defer a.mu.Unlock() return a.doRemoveWithoutLock(index) } // doRemoveWithoutLock removes an item by index without lock. -func (a *SortedArray) doRemoveWithoutLock(index int) (value interface{}, found bool) { +func (a *SortedArray) doRemoveWithoutLock(index int) (value any, found bool) { if index < 0 || index >= len(a.array) { return nil, false } @@ -206,7 +206,7 @@ func (a *SortedArray) doRemoveWithoutLock(index int) (value interface{}, found b // RemoveValue removes an item by value. // It returns true if value is found in the array, or else false if not found. -func (a *SortedArray) RemoveValue(value interface{}) bool { +func (a *SortedArray) RemoveValue(value any) bool { a.mu.Lock() defer a.mu.Unlock() if i, r := a.binSearch(value, false); r == 0 { @@ -217,7 +217,7 @@ func (a *SortedArray) RemoveValue(value interface{}) bool { } // RemoveValues removes an item by `values`. -func (a *SortedArray) RemoveValues(values ...interface{}) { +func (a *SortedArray) RemoveValues(values ...any) { a.mu.Lock() defer a.mu.Unlock() for _, value := range values { @@ -229,7 +229,7 @@ func (a *SortedArray) RemoveValues(values ...interface{}) { // PopLeft pops and returns an item from the beginning of array. // Note that if the array is empty, the `found` is false. -func (a *SortedArray) PopLeft() (value interface{}, found bool) { +func (a *SortedArray) PopLeft() (value any, found bool) { a.mu.Lock() defer a.mu.Unlock() if len(a.array) == 0 { @@ -242,7 +242,7 @@ func (a *SortedArray) PopLeft() (value interface{}, found bool) { // PopRight pops and returns an item from the end of array. // Note that if the array is empty, the `found` is false. -func (a *SortedArray) PopRight() (value interface{}, found bool) { +func (a *SortedArray) PopRight() (value any, found bool) { a.mu.Lock() defer a.mu.Unlock() index := len(a.array) - 1 @@ -256,14 +256,14 @@ func (a *SortedArray) PopRight() (value interface{}, found bool) { // PopRand randomly pops and return an item out of array. // Note that if the array is empty, the `found` is false. -func (a *SortedArray) PopRand() (value interface{}, found bool) { +func (a *SortedArray) PopRand() (value any, found bool) { a.mu.Lock() defer a.mu.Unlock() return a.doRemoveWithoutLock(grand.Intn(len(a.array))) } // PopRands randomly pops and returns `size` items out of array. -func (a *SortedArray) PopRands(size int) []interface{} { +func (a *SortedArray) PopRands(size int) []any { a.mu.Lock() defer a.mu.Unlock() if size <= 0 || len(a.array) == 0 { @@ -272,7 +272,7 @@ func (a *SortedArray) PopRands(size int) []interface{} { if size >= len(a.array) { size = len(a.array) } - array := make([]interface{}, size) + array := make([]any, size) for i := 0; i < size; i++ { array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array))) } @@ -280,7 +280,7 @@ func (a *SortedArray) PopRands(size int) []interface{} { } // PopLefts pops and returns `size` items from the beginning of array. -func (a *SortedArray) PopLefts(size int) []interface{} { +func (a *SortedArray) PopLefts(size int) []any { a.mu.Lock() defer a.mu.Unlock() if size <= 0 || len(a.array) == 0 { @@ -297,7 +297,7 @@ func (a *SortedArray) PopLefts(size int) []interface{} { } // PopRights pops and returns `size` items from the end of array. -func (a *SortedArray) PopRights(size int) []interface{} { +func (a *SortedArray) PopRights(size int) []any { a.mu.Lock() defer a.mu.Unlock() if size <= 0 || len(a.array) == 0 { @@ -321,7 +321,7 @@ func (a *SortedArray) PopRights(size int) []interface{} { // If `end` is negative, then the offset will start from the end of array. // If `end` is omitted, then the sequence will have everything from start up // until the end of the array. -func (a *SortedArray) Range(start int, end ...int) []interface{} { +func (a *SortedArray) Range(start int, end ...int) []any { a.mu.RLock() defer a.mu.RUnlock() offsetEnd := len(a.array) @@ -334,9 +334,9 @@ func (a *SortedArray) Range(start int, end ...int) []interface{} { if start < 0 { start = 0 } - array := ([]interface{})(nil) + array := ([]any)(nil) if a.mu.IsSafe() { - array = make([]interface{}, offsetEnd-start) + array = make([]any, offsetEnd-start) copy(array, a.array[start:offsetEnd]) } else { array = a.array[start:offsetEnd] @@ -357,7 +357,7 @@ func (a *SortedArray) Range(start int, end ...int) []interface{} { // If it is omitted, then the sequence will have everything from offset up until the end of the array. // // Any possibility crossing the left border of array, it will fail. -func (a *SortedArray) SubSlice(offset int, length ...int) []interface{} { +func (a *SortedArray) SubSlice(offset int, length ...int) []any { a.mu.RLock() defer a.mu.RUnlock() size := len(a.array) @@ -386,7 +386,7 @@ func (a *SortedArray) SubSlice(offset int, length ...int) []interface{} { size = len(a.array) - offset } if a.mu.IsSafe() { - s := make([]interface{}, size) + s := make([]any, size) copy(s, a.array[offset:]) return s } else { @@ -415,12 +415,12 @@ func (a *SortedArray) Len() int { // Slice returns the underlying data of array. // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // or else a pointer to the underlying data. -func (a *SortedArray) Slice() []interface{} { - var array []interface{} +func (a *SortedArray) Slice() []any { + var array []any if a.mu.IsSafe() { a.mu.RLock() defer a.mu.RUnlock() - array = make([]interface{}, len(a.array)) + array = make([]any, len(a.array)) copy(array, a.array) } else { array = a.array @@ -428,19 +428,19 @@ func (a *SortedArray) Slice() []interface{} { return array } -// Interfaces returns current array as []interface{}. -func (a *SortedArray) Interfaces() []interface{} { +// Interfaces returns current array as []any. +func (a *SortedArray) Interfaces() []any { return a.Slice() } // Contains checks whether a value exists in the array. -func (a *SortedArray) Contains(value interface{}) bool { +func (a *SortedArray) Contains(value any) bool { return a.Search(value) != -1 } // Search searches array by `value`, returns the index of `value`, // or returns -1 if not exists. -func (a *SortedArray) Search(value interface{}) (index int) { +func (a *SortedArray) Search(value any) (index int) { if i, r := a.binSearch(value, true); r == 0 { return i } @@ -452,7 +452,7 @@ func (a *SortedArray) Search(value interface{}) (index int) { // If `result` equals to 0, it means the value at `index` is equals to `value`. // If `result` lesser than 0, it means the value at `index` is lesser than `value`. // If `result` greater than 0, it means the value at `index` is greater than `value`. -func (a *SortedArray) binSearch(value interface{}, lock bool) (index int, result int) { +func (a *SortedArray) binSearch(value any, lock bool) (index int, result int) { if lock { a.mu.RLock() defer a.mu.RUnlock() @@ -515,7 +515,7 @@ func (a *SortedArray) Unique() *SortedArray { // Clone returns a new array, which is a copy of current array. func (a *SortedArray) Clone() (newArray *SortedArray) { a.mu.RLock() - array := make([]interface{}, len(a.array)) + array := make([]any, len(a.array)) copy(array, a.array) a.mu.RUnlock() return NewSortedArrayFrom(array, a.comparator, a.mu.IsSafe()) @@ -525,14 +525,14 @@ func (a *SortedArray) Clone() (newArray *SortedArray) { func (a *SortedArray) Clear() *SortedArray { a.mu.Lock() if len(a.array) > 0 { - a.array = make([]interface{}, 0) + a.array = make([]any, 0) } a.mu.Unlock() return a } // LockFunc locks writing by callback function `f`. -func (a *SortedArray) LockFunc(f func(array []interface{})) *SortedArray { +func (a *SortedArray) LockFunc(f func(array []any)) *SortedArray { a.mu.Lock() defer a.mu.Unlock() @@ -546,7 +546,7 @@ func (a *SortedArray) LockFunc(f func(array []interface{})) *SortedArray { } // RLockFunc locks reading by callback function `f`. -func (a *SortedArray) RLockFunc(f func(array []interface{})) *SortedArray { +func (a *SortedArray) RLockFunc(f func(array []any)) *SortedArray { a.mu.RLock() defer a.mu.RUnlock() f(a.array) @@ -557,14 +557,14 @@ func (a *SortedArray) RLockFunc(f func(array []interface{})) *SortedArray { // The parameter `array` can be any garray or slice type. // The difference between Merge and Append is Append supports only specified slice type, // but Merge supports more parameter types. -func (a *SortedArray) Merge(array interface{}) *SortedArray { +func (a *SortedArray) Merge(array any) *SortedArray { return a.Add(gconv.Interfaces(array)...) } // Chunk splits an array into multiple arrays, // the size of each array is determined by `size`. // The last chunk may contain less than size elements. -func (a *SortedArray) Chunk(size int) [][]interface{} { +func (a *SortedArray) Chunk(size int) [][]any { if size < 1 { return nil } @@ -572,7 +572,7 @@ func (a *SortedArray) Chunk(size int) [][]interface{} { defer a.mu.RUnlock() length := len(a.array) chunks := int(math.Ceil(float64(length) / float64(size))) - var n [][]interface{} + var n [][]any for i, end := 0, 0; chunks > 0; chunks-- { end = (i + 1) * size if end > length { @@ -585,7 +585,7 @@ func (a *SortedArray) Chunk(size int) [][]interface{} { } // Rand randomly returns one item from array(no deleting). -func (a *SortedArray) Rand() (value interface{}, found bool) { +func (a *SortedArray) Rand() (value any, found bool) { a.mu.RLock() defer a.mu.RUnlock() if len(a.array) == 0 { @@ -595,13 +595,13 @@ func (a *SortedArray) Rand() (value interface{}, found bool) { } // Rands randomly returns `size` items from array(no deleting). -func (a *SortedArray) Rands(size int) []interface{} { +func (a *SortedArray) Rands(size int) []any { a.mu.RLock() defer a.mu.RUnlock() if size <= 0 || len(a.array) == 0 { return nil } - array := make([]interface{}, size) + array := make([]any, size) for i := 0; i < size; i++ { array[i] = a.array[grand.Intn(len(a.array))] } @@ -626,8 +626,8 @@ func (a *SortedArray) Join(glue string) string { } // CountValues counts the number of occurrences of all values in the array. -func (a *SortedArray) CountValues() map[interface{}]int { - m := make(map[interface{}]int) +func (a *SortedArray) CountValues() map[any]int { + m := make(map[any]int) a.mu.RLock() defer a.mu.RUnlock() for _, v := range a.array { @@ -637,13 +637,13 @@ func (a *SortedArray) CountValues() map[interface{}]int { } // Iterator is alias of IteratorAsc. -func (a *SortedArray) Iterator(f func(k int, v interface{}) bool) { +func (a *SortedArray) Iterator(f func(k int, v any) bool) { a.IteratorAsc(f) } // IteratorAsc iterates the array readonly in ascending order with given callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. -func (a *SortedArray) IteratorAsc(f func(k int, v interface{}) bool) { +func (a *SortedArray) IteratorAsc(f func(k int, v any) bool) { a.mu.RLock() defer a.mu.RUnlock() for k, v := range a.array { @@ -655,7 +655,7 @@ func (a *SortedArray) IteratorAsc(f func(k int, v interface{}) bool) { // IteratorDesc iterates the array readonly in descending order with given callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. -func (a *SortedArray) IteratorDesc(f func(k int, v interface{}) bool) { +func (a *SortedArray) IteratorDesc(f func(k int, v any) bool) { a.mu.RLock() defer a.mu.RUnlock() for i := len(a.array) - 1; i >= 0; i-- { @@ -702,7 +702,7 @@ func (a SortedArray) MarshalJSON() ([]byte, error) { // Note that the comparator is set as string comparator in default. func (a *SortedArray) UnmarshalJSON(b []byte) error { if a.comparator == nil { - a.array = make([]interface{}, 0) + a.array = make([]any, 0) a.comparator = gutil.ComparatorString } a.mu.Lock() @@ -720,7 +720,7 @@ func (a *SortedArray) UnmarshalJSON(b []byte) error { // UnmarshalValue is an interface implement which sets any type of value for array. // Note that the comparator is set as string comparator in default. -func (a *SortedArray) UnmarshalValue(value interface{}) (err error) { +func (a *SortedArray) UnmarshalValue(value any) (err error) { if a.comparator == nil { a.comparator = gutil.ComparatorString } @@ -764,7 +764,7 @@ func (a *SortedArray) FilterNil() *SortedArray { // Filter iterates array and filters elements using custom callback function. // It removes the element from array if callback function `filter` returns true, // it or else does nothing and continues iterating. -func (a *SortedArray) Filter(filter func(index int, value interface{}) bool) *SortedArray { +func (a *SortedArray) Filter(filter func(index int, value any) bool) *SortedArray { a.mu.Lock() defer a.mu.Unlock() for i := 0; i < len(a.array); { @@ -800,7 +800,7 @@ func (a *SortedArray) FilterEmpty() *SortedArray { } // Walk applies a user supplied function `f` to every item of array. -func (a *SortedArray) Walk(f func(value interface{}) interface{}) *SortedArray { +func (a *SortedArray) Walk(f func(value any) any) *SortedArray { a.mu.Lock() defer a.mu.Unlock() // Keep the array always sorted. @@ -820,7 +820,7 @@ func (a *SortedArray) IsEmpty() bool { // getComparator returns the comparator if it's previously set, // or else it panics. -func (a *SortedArray) getComparator() func(a, b interface{}) int { +func (a *SortedArray) getComparator() func(a, b any) int { if a.comparator == nil { panic("comparator is missing for sorted array") } @@ -828,13 +828,13 @@ func (a *SortedArray) getComparator() func(a, b interface{}) int { } // DeepCopy implements interface for deep copy of current type. -func (a *SortedArray) DeepCopy() interface{} { +func (a *SortedArray) DeepCopy() any { if a == nil { return nil } a.mu.RLock() defer a.mu.RUnlock() - newSlice := make([]interface{}, len(a.array)) + newSlice := make([]any, len(a.array)) for i, v := range a.array { newSlice[i] = deepcopy.Copy(v) } diff --git a/container/garray/garray_sorted_int.go b/container/garray/garray_sorted_int.go index b9181aea3f2..6fdc67f110d 100644 --- a/container/garray/garray_sorted_int.go +++ b/container/garray/garray_sorted_int.go @@ -420,11 +420,11 @@ func (a *SortedIntArray) Slice() []int { return array } -// Interfaces returns current array as []interface{}. -func (a *SortedIntArray) Interfaces() []interface{} { +// Interfaces returns current array as []any. +func (a *SortedIntArray) Interfaces() []any { a.mu.RLock() defer a.mu.RUnlock() - array := make([]interface{}, len(a.array)) + array := make([]any, len(a.array)) for k, v := range a.array { array[k] = v } @@ -549,7 +549,7 @@ func (a *SortedIntArray) RLockFunc(f func(array []int)) *SortedIntArray { // The parameter `array` can be any garray or slice type. // The difference between Merge and Append is Append supports only specified slice type, // but Merge supports more parameter types. -func (a *SortedIntArray) Merge(array interface{}) *SortedIntArray { +func (a *SortedIntArray) Merge(array any) *SortedIntArray { return a.Add(gconv.Ints(array)...) } @@ -691,7 +691,7 @@ func (a *SortedIntArray) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for array. -func (a *SortedIntArray) UnmarshalValue(value interface{}) (err error) { +func (a *SortedIntArray) UnmarshalValue(value any) (err error) { if a.comparator == nil { a.comparator = defaultComparatorInt } @@ -775,7 +775,7 @@ func (a *SortedIntArray) getComparator() func(a, b int) int { } // DeepCopy implements interface for deep copy of current type. -func (a *SortedIntArray) DeepCopy() interface{} { +func (a *SortedIntArray) DeepCopy() any { if a == nil { return nil } diff --git a/container/garray/garray_sorted_str.go b/container/garray/garray_sorted_str.go index fa00b7c7107..8a4973d0b17 100644 --- a/container/garray/garray_sorted_str.go +++ b/container/garray/garray_sorted_str.go @@ -406,11 +406,11 @@ func (a *SortedStrArray) Slice() []string { return array } -// Interfaces returns current array as []interface{}. -func (a *SortedStrArray) Interfaces() []interface{} { +// Interfaces returns current array as []any. +func (a *SortedStrArray) Interfaces() []any { a.mu.RLock() defer a.mu.RUnlock() - array := make([]interface{}, len(a.array)) + array := make([]any, len(a.array)) for k, v := range a.array { array[k] = v } @@ -551,7 +551,7 @@ func (a *SortedStrArray) RLockFunc(f func(array []string)) *SortedStrArray { // The parameter `array` can be any garray or slice type. // The difference between Merge and Append is Append supports only specified slice type, // but Merge supports more parameter types. -func (a *SortedStrArray) Merge(array interface{}) *SortedStrArray { +func (a *SortedStrArray) Merge(array any) *SortedStrArray { return a.Add(gconv.Strings(array)...) } @@ -704,7 +704,7 @@ func (a *SortedStrArray) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for array. -func (a *SortedStrArray) UnmarshalValue(value interface{}) (err error) { +func (a *SortedStrArray) UnmarshalValue(value any) (err error) { if a.comparator == nil { a.comparator = defaultComparatorStr } @@ -788,7 +788,7 @@ func (a *SortedStrArray) getComparator() func(a, b string) int { } // DeepCopy implements interface for deep copy of current type. -func (a *SortedStrArray) DeepCopy() interface{} { +func (a *SortedStrArray) DeepCopy() any { if a == nil { return nil } diff --git a/container/garray/garray_z_bench_any_test.go b/container/garray/garray_z_bench_any_test.go index b316e23b5fc..1c795b56f63 100644 --- a/container/garray/garray_z_bench_any_test.go +++ b/container/garray/garray_z_bench_any_test.go @@ -14,12 +14,12 @@ import ( type anySortedArrayItem struct { priority int64 - value interface{} + value any } var ( anyArray = garray.NewArray() - anySortedArray = garray.NewSortedArray(func(a, b interface{}) int { + anySortedArray = garray.NewSortedArray(func(a, b any) int { return int(a.(anySortedArrayItem).priority - b.(anySortedArrayItem).priority) }) ) diff --git a/container/garray/garray_z_example_normal_any_test.go b/container/garray/garray_z_example_normal_any_test.go index a115fcacf8e..06e74f571e5 100644 --- a/container/garray/garray_z_example_normal_any_test.go +++ b/container/garray/garray_z_example_normal_any_test.go @@ -81,13 +81,13 @@ func ExampleArray_Iterator() { // Iterator is alias of IteratorAsc, which iterates the array readonly in ascending order // with given callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. - array.Iterator(func(k int, v interface{}) bool { + array.Iterator(func(k int, v any) bool { fmt.Println(k, v) return true }) // IteratorDesc iterates the array readonly in descending order with given callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. - array.IteratorDesc(func(k int, v interface{}) bool { + array.IteratorDesc(func(k int, v any) bool { fmt.Println(k, v) return true }) @@ -163,7 +163,7 @@ func ExampleArray_Chunk() { } func ExampleArray_PopLeft() { - array := garray.NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) + array := garray.NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9}) // Any Pop* functions pick, delete and return the item from array. @@ -180,7 +180,7 @@ func ExampleArray_PopLeft() { } func ExampleArray_PopLefts() { - array := garray.NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) + array := garray.NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9}) // Any Pop* functions pick, delete and return the item from array. @@ -197,7 +197,7 @@ func ExampleArray_PopLefts() { } func ExampleArray_PopRight() { - array := garray.NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) + array := garray.NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9}) // Any Pop* functions pick, delete and return the item from array. @@ -214,7 +214,7 @@ func ExampleArray_PopRight() { } func ExampleArray_PopRights() { - array := garray.NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) + array := garray.NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9}) // Any Pop* functions pick, delete and return the item from array. @@ -265,10 +265,10 @@ func ExampleArray_Merge() { func ExampleArray_Filter() { array1 := garray.NewFrom(g.Slice{0, 1, 2, nil, "", g.Slice{}, "john"}) array2 := garray.NewFrom(g.Slice{0, 1, 2, nil, "", g.Slice{}, "john"}) - fmt.Printf("%#v\n", array1.Filter(func(index int, value interface{}) bool { + fmt.Printf("%#v\n", array1.Filter(func(index int, value any) bool { return empty.IsNil(value) }).Slice()) - fmt.Printf("%#v\n", array2.Filter(func(index int, value interface{}) bool { + fmt.Printf("%#v\n", array2.Filter(func(index int, value any) bool { return empty.IsEmpty(value) }).Slice()) diff --git a/container/garray/garray_z_unit_all_basic_test.go b/container/garray/garray_z_unit_all_basic_test.go index 1fff15620be..5c76233fff5 100644 --- a/container/garray/garray_z_unit_all_basic_test.go +++ b/container/garray/garray_z_unit_all_basic_test.go @@ -131,7 +131,7 @@ func Test_SortedStrArray2(t *testing.T) { func Test_SortedArray1(t *testing.T) { gtest.C(t, func(t *gtest.T) { expect := []string{"0", "1", "10", "2", "3", "4", "5", "6", "7", "8", "9"} - array := garray.NewSortedArray(func(v1, v2 interface{}) int { + array := garray.NewSortedArray(func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) }) for i := 10; i > -1; i-- { @@ -144,7 +144,7 @@ func Test_SortedArray1(t *testing.T) { func Test_SortedArray2(t *testing.T) { gtest.C(t, func(t *gtest.T) { expect := []string{"0", "1", "10", "2", "3", "4", "5", "6", "7", "8", "9"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array := garray.NewSortedArray(func1) @@ -161,7 +161,7 @@ func Test_SortedArray2(t *testing.T) { func TestNewFromCopy(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"100", "200", "300", "400", "500", "600"} + a1 := []any{"100", "200", "300", "400", "500", "600"} array1 := garray.NewFromCopy(a1) t.AssertIN(array1.PopRands(2), a1) t.Assert(len(array1.PopRands(1)), 1) diff --git a/container/garray/garray_z_unit_normal_any_test.go b/container/garray/garray_z_unit_normal_any_test.go index 5cce7794981..7d09145dfd3 100644 --- a/container/garray/garray_z_unit_normal_any_test.go +++ b/container/garray/garray_z_unit_normal_any_test.go @@ -22,10 +22,10 @@ import ( func Test_Array_Basic(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := []interface{}{0, 1, 2, 3} + expect := []any{0, 1, 2, 3} array := garray.NewArrayFrom(expect) array2 := garray.NewArrayFrom(expect) - array3 := garray.NewArrayFrom([]interface{}{}) + array3 := garray.NewArrayFrom([]any{}) array4 := garray.NewArrayRange(1, 5, 1) t.Assert(array.Slice(), expect) @@ -86,10 +86,10 @@ func Test_Array_Basic(t *testing.T) { t.Assert(array.Len(), 4) array.InsertBefore(0, 100) array.InsertAfter(0, 200) - t.Assert(array.Slice(), []interface{}{100, 200, 2, 2, 3, 4}) + t.Assert(array.Slice(), []any{100, 200, 2, 2, 3, 4}) array.InsertBefore(5, 300) array.InsertAfter(6, 400) - t.Assert(array.Slice(), []interface{}{100, 200, 2, 2, 3, 300, 4, 400}) + t.Assert(array.Slice(), []any{100, 200, 2, 2, 3, 300, 4, 400}) t.Assert(array.Clear().Len(), 0) err = array.InsertBefore(99, 9900) t.AssertNE(err, nil) @@ -102,17 +102,17 @@ func Test_Array_Basic(t *testing.T) { func TestArray_Sort(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect1 := []interface{}{0, 1, 2, 3} - expect2 := []interface{}{3, 2, 1, 0} + expect1 := []any{0, 1, 2, 3} + expect2 := []any{3, 2, 1, 0} array := garray.NewArray() for i := 3; i >= 0; i-- { array.Append(i) } - array.SortFunc(func(v1, v2 interface{}) bool { + array.SortFunc(func(v1, v2 any) bool { return v1.(int) < v2.(int) }) t.Assert(array.Slice(), expect1) - array.SortFunc(func(v1, v2 interface{}) bool { + array.SortFunc(func(v1, v2 any) bool { return v1.(int) > v2.(int) }) t.Assert(array.Slice(), expect2) @@ -121,20 +121,20 @@ func TestArray_Sort(t *testing.T) { func TestArray_Unique(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := []interface{}{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5} + expect := []any{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5} array := garray.NewArrayFrom(expect) - t.Assert(array.Unique().Slice(), []interface{}{1, 2, 3, 4, 5}) + t.Assert(array.Unique().Slice(), []any{1, 2, 3, 4, 5}) }) gtest.C(t, func(t *gtest.T) { - expect := []interface{}{} + expect := []any{} array := garray.NewArrayFrom(expect) - t.Assert(array.Unique().Slice(), []interface{}{}) + t.Assert(array.Unique().Slice(), []any{}) }) } func TestArray_PushAndPop(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := []interface{}{0, 1, 2, 3} + expect := []any{0, 1, 2, 3} array := garray.NewArrayFrom(expect) t.Assert(array.Slice(), expect) @@ -147,24 +147,24 @@ func TestArray_PushAndPop(t *testing.T) { t.Assert(ok, true) v, ok = array.PopRand() - t.AssertIN(v, []interface{}{1, 2}) + t.AssertIN(v, []any{1, 2}) t.Assert(ok, true) v, ok = array.PopRand() - t.AssertIN(v, []interface{}{1, 2}) + t.AssertIN(v, []any{1, 2}) t.Assert(ok, true) t.Assert(array.Len(), 0) array.PushLeft(1).PushRight(2) - t.Assert(array.Slice(), []interface{}{1, 2}) + t.Assert(array.Slice(), []any{1, 2}) }) } func TestArray_PopRands(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{100, 200, 300, 400, 500, 600} + a1 := []any{100, 200, 300, 400, 500, 600} array := garray.NewFromCopy(a1) - t.AssertIN(array.PopRands(2), []interface{}{100, 200, 300, 400, 500, 600}) + t.AssertIN(array.PopRands(2), []any{100, 200, 300, 400, 500, 600}) }) } @@ -247,56 +247,56 @@ func TestArray_PopLeftsAndPopRights(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - value1 := []interface{}{0, 1, 2, 3, 4, 5, 6} - value2 := []interface{}{0, 1, 2, 3, 4, 5, 6} + value1 := []any{0, 1, 2, 3, 4, 5, 6} + value2 := []any{0, 1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(value1) array2 := garray.NewArrayFrom(value2) - t.Assert(array1.PopLefts(2), []interface{}{0, 1}) - t.Assert(array1.Slice(), []interface{}{2, 3, 4, 5, 6}) - t.Assert(array1.PopRights(2), []interface{}{5, 6}) - t.Assert(array1.Slice(), []interface{}{2, 3, 4}) - t.Assert(array1.PopRights(20), []interface{}{2, 3, 4}) - t.Assert(array1.Slice(), []interface{}{}) - t.Assert(array2.PopLefts(20), []interface{}{0, 1, 2, 3, 4, 5, 6}) - t.Assert(array2.Slice(), []interface{}{}) + t.Assert(array1.PopLefts(2), []any{0, 1}) + t.Assert(array1.Slice(), []any{2, 3, 4, 5, 6}) + t.Assert(array1.PopRights(2), []any{5, 6}) + t.Assert(array1.Slice(), []any{2, 3, 4}) + t.Assert(array1.PopRights(20), []any{2, 3, 4}) + t.Assert(array1.Slice(), []any{}) + t.Assert(array2.PopLefts(20), []any{0, 1, 2, 3, 4, 5, 6}) + t.Assert(array2.Slice(), []any{}) }) } func TestArray_Range(t *testing.T) { gtest.C(t, func(t *gtest.T) { - value1 := []interface{}{0, 1, 2, 3, 4, 5, 6} + value1 := []any{0, 1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(value1) array2 := garray.NewArrayFrom(value1, true) - t.Assert(array1.Range(0, 1), []interface{}{0}) - t.Assert(array1.Range(1, 2), []interface{}{1}) - t.Assert(array1.Range(0, 2), []interface{}{0, 1}) + t.Assert(array1.Range(0, 1), []any{0}) + t.Assert(array1.Range(1, 2), []any{1}) + t.Assert(array1.Range(0, 2), []any{0, 1}) t.Assert(array1.Range(-1, 10), value1) t.Assert(array1.Range(10, 2), nil) - t.Assert(array2.Range(1, 3), []interface{}{1, 2}) + t.Assert(array2.Range(1, 3), []any{1, 2}) }) } func TestArray_Merge(t *testing.T) { gtest.C(t, func(t *gtest.T) { - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { if gconv.Int(v1) < gconv.Int(v2) { return 0 } return 1 } - i1 := []interface{}{0, 1, 2, 3} - i2 := []interface{}{4, 5, 6, 7} + i1 := []any{0, 1, 2, 3} + i2 := []any{4, 5, 6, 7} array1 := garray.NewArrayFrom(i1) array2 := garray.NewArrayFrom(i2) - t.Assert(array1.Merge(array2).Slice(), []interface{}{0, 1, 2, 3, 4, 5, 6, 7}) + t.Assert(array1.Merge(array2).Slice(), []any{0, 1, 2, 3, 4, 5, 6, 7}) // s1 := []string{"a", "b", "c", "d"} s2 := []string{"e", "f"} i3 := garray.NewIntArrayFrom([]int{1, 2, 3}) - i4 := garray.NewArrayFrom([]interface{}{3}) + i4 := garray.NewArrayFrom([]any{3}) s3 := garray.NewStrArrayFrom([]string{"g", "h"}) - s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) + s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1) s5 := garray.NewSortedStrArrayFrom(s2) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) a1 := garray.NewArrayFrom(i1) @@ -313,92 +313,92 @@ func TestArray_Merge(t *testing.T) { func TestArray_Fill(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0} - a2 := []interface{}{0} + a1 := []any{0} + a2 := []any{0} array1 := garray.NewArrayFrom(a1) array2 := garray.NewArrayFrom(a2, true) t.Assert(array1.Fill(1, 2, 100), nil) - t.Assert(array1.Slice(), []interface{}{0, 100, 100}) + t.Assert(array1.Slice(), []any{0, 100, 100}) t.Assert(array2.Fill(0, 2, 100), nil) - t.Assert(array2.Slice(), []interface{}{100, 100}) + t.Assert(array2.Slice(), []any{100, 100}) t.AssertNE(array2.Fill(-1, 2, 100), nil) - t.Assert(array2.Slice(), []interface{}{100, 100}) + t.Assert(array2.Slice(), []any{100, 100}) }) } func TestArray_Chunk(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{1, 2, 3, 4, 5} + a1 := []any{1, 2, 3, 4, 5} array1 := garray.NewArrayFrom(a1) chunks := array1.Chunk(2) t.Assert(len(chunks), 3) - t.Assert(chunks[0], []interface{}{1, 2}) - t.Assert(chunks[1], []interface{}{3, 4}) - t.Assert(chunks[2], []interface{}{5}) + t.Assert(chunks[0], []any{1, 2}) + t.Assert(chunks[1], []any{3, 4}) + t.Assert(chunks[2], []any{5}) t.Assert(array1.Chunk(0), nil) }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{1, 2, 3, 4, 5} + a1 := []any{1, 2, 3, 4, 5} array1 := garray.NewArrayFrom(a1) chunks := array1.Chunk(3) t.Assert(len(chunks), 2) - t.Assert(chunks[0], []interface{}{1, 2, 3}) - t.Assert(chunks[1], []interface{}{4, 5}) + t.Assert(chunks[0], []any{1, 2, 3}) + t.Assert(chunks[1], []any{4, 5}) t.Assert(array1.Chunk(0), nil) }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{1, 2, 3, 4, 5, 6} + a1 := []any{1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(a1) chunks := array1.Chunk(2) t.Assert(len(chunks), 3) - t.Assert(chunks[0], []interface{}{1, 2}) - t.Assert(chunks[1], []interface{}{3, 4}) - t.Assert(chunks[2], []interface{}{5, 6}) + t.Assert(chunks[0], []any{1, 2}) + t.Assert(chunks[1], []any{3, 4}) + t.Assert(chunks[2], []any{5, 6}) t.Assert(array1.Chunk(0), nil) }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{1, 2, 3, 4, 5, 6} + a1 := []any{1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(a1) chunks := array1.Chunk(3) t.Assert(len(chunks), 2) - t.Assert(chunks[0], []interface{}{1, 2, 3}) - t.Assert(chunks[1], []interface{}{4, 5, 6}) + t.Assert(chunks[0], []any{1, 2, 3}) + t.Assert(chunks[1], []any{4, 5, 6}) t.Assert(array1.Chunk(0), nil) }) } func TestArray_Pad(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0} + a1 := []any{0} array1 := garray.NewArrayFrom(a1) - t.Assert(array1.Pad(3, 1).Slice(), []interface{}{0, 1, 1}) - t.Assert(array1.Pad(-4, 1).Slice(), []interface{}{1, 0, 1, 1}) - t.Assert(array1.Pad(3, 1).Slice(), []interface{}{1, 0, 1, 1}) + t.Assert(array1.Pad(3, 1).Slice(), []any{0, 1, 1}) + t.Assert(array1.Pad(-4, 1).Slice(), []any{1, 0, 1, 1}) + t.Assert(array1.Pad(3, 1).Slice(), []any{1, 0, 1, 1}) }) } func TestArray_SubSlice(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} + a1 := []any{0, 1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(a1) array2 := garray.NewArrayFrom(a1, true) - t.Assert(array1.SubSlice(0, 2), []interface{}{0, 1}) - t.Assert(array1.SubSlice(2, 2), []interface{}{2, 3}) - t.Assert(array1.SubSlice(5, 8), []interface{}{5, 6}) + t.Assert(array1.SubSlice(0, 2), []any{0, 1}) + t.Assert(array1.SubSlice(2, 2), []any{2, 3}) + t.Assert(array1.SubSlice(5, 8), []any{5, 6}) t.Assert(array1.SubSlice(9, 1), nil) - t.Assert(array1.SubSlice(-2, 2), []interface{}{5, 6}) + t.Assert(array1.SubSlice(-2, 2), []any{5, 6}) t.Assert(array1.SubSlice(-9, 2), nil) t.Assert(array1.SubSlice(1, -2), nil) - t.Assert(array2.SubSlice(0, 2), []interface{}{0, 1}) + t.Assert(array2.SubSlice(0, 2), []any{0, 1}) }) } func TestArray_Rand(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} + a1 := []any{0, 1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(a1) t.Assert(len(array1.Rands(2)), 2) t.Assert(len(array1.Rands(10)), 10) @@ -406,7 +406,7 @@ func TestArray_Rand(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - s1 := []interface{}{"a", "b", "c", "d"} + s1 := []any{"a", "b", "c", "d"} a1 := garray.NewArrayFrom(s1) i1, ok := a1.Rand() t.Assert(ok, true) @@ -415,7 +415,7 @@ func TestArray_Rand(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{} + a1 := []any{} array1 := garray.NewArrayFrom(a1) rand, found := array1.Rand() t.AssertNil(rand) @@ -423,7 +423,7 @@ func TestArray_Rand(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{} + a1 := []any{} array1 := garray.NewArrayFrom(a1) rand := array1.Rands(1) t.AssertNil(rand) @@ -432,7 +432,7 @@ func TestArray_Rand(t *testing.T) { func TestArray_Shuffle(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} + a1 := []any{0, 1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(a1) t.Assert(array1.Shuffle().Len(), 7) }) @@ -440,27 +440,27 @@ func TestArray_Shuffle(t *testing.T) { func TestArray_Reverse(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} + a1 := []any{0, 1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(a1) - t.Assert(array1.Reverse().Slice(), []interface{}{6, 5, 4, 3, 2, 1, 0}) + t.Assert(array1.Reverse().Slice(), []any{6, 5, 4, 3, 2, 1, 0}) }) } func TestArray_Join(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} + a1 := []any{0, 1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(a1) t.Assert(array1.Join("."), `0.1.2.3.4.5.6`) }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, `"a"`, `\a`} + a1 := []any{0, 1, `"a"`, `\a`} array1 := garray.NewArrayFrom(a1) t.Assert(array1.Join("."), `0.1."a".\a`) }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{} + a1 := []any{} array1 := garray.NewArrayFrom(a1) t.Assert(len(array1.Join(".")), 0) }) @@ -468,7 +468,7 @@ func TestArray_Join(t *testing.T) { func TestArray_String(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} + a1 := []any{0, 1, 2, 3, 4, 5, 6} array1 := garray.NewArrayFrom(a1) t.Assert(array1.String(), `[0,1,2,3,4,5,6]`) array1 = nil @@ -478,9 +478,9 @@ func TestArray_String(t *testing.T) { func TestArray_Replace(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} - a2 := []interface{}{"a", "b", "c"} - a3 := []interface{}{"m", "n", "p", "z", "x", "y", "d", "u"} + a1 := []any{0, 1, 2, 3, 4, 5, 6} + a2 := []any{"a", "b", "c"} + a3 := []any{"m", "n", "p", "z", "x", "y", "d", "u"} array1 := garray.NewArrayFrom(a1) array2 := array1.Replace(a2) t.Assert(array2.Len(), 7) @@ -497,8 +497,8 @@ func TestArray_Replace(t *testing.T) { func TestArray_SetArray(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3, 4, 5, 6} - a2 := []interface{}{"a", "b", "c"} + a1 := []any{0, 1, 2, 3, 4, 5, 6} + a2 := []any{"a", "b", "c"} array1 := garray.NewArrayFrom(a1) array1 = array1.SetArray(a2) @@ -510,9 +510,9 @@ func TestArray_SetArray(t *testing.T) { func TestArray_Sum(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3} - a2 := []interface{}{"a", "b", "c"} - a3 := []interface{}{"a", "1", "2"} + a1 := []any{0, 1, 2, 3} + a2 := []any{"a", "b", "c"} + a3 := []any{"a", "1", "2"} array1 := garray.NewArrayFrom(a1) array2 := garray.NewArrayFrom(a2) @@ -527,7 +527,7 @@ func TestArray_Sum(t *testing.T) { func TestArray_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, 2, 3} + a1 := []any{0, 1, 2, 3} array1 := garray.NewArrayFrom(a1) array2 := array1.Clone() @@ -540,7 +540,7 @@ func TestArray_Clone(t *testing.T) { func TestArray_CountValues(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "b", "c", "d", "e", "d"} + a1 := []any{"a", "b", "c", "d", "e", "d"} array1 := garray.NewArrayFrom(a1) array2 := array1.CountValues() t.Assert(len(array2), 5) @@ -551,13 +551,13 @@ func TestArray_CountValues(t *testing.T) { func TestArray_LockFunc(t *testing.T) { gtest.C(t, func(t *gtest.T) { - s1 := []interface{}{"a", "b", "c", "d"} + s1 := []any{"a", "b", "c", "d"} a1 := garray.NewArrayFrom(s1, true) ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) // go1 - go a1.LockFunc(func(n1 []interface{}) { // 读写锁 + go a1.LockFunc(func(n1 []any) { // 读写锁 time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -583,13 +583,13 @@ func TestArray_LockFunc(t *testing.T) { func TestArray_RLockFunc(t *testing.T) { gtest.C(t, func(t *gtest.T) { - s1 := []interface{}{"a", "b", "c", "d"} + s1 := []any{"a", "b", "c", "d"} a1 := garray.NewArrayFrom(s1, true) ch1 := make(chan int64, 3) ch2 := make(chan int64, 1) // go1 - go a1.RLockFunc(func(n1 []interface{}) { // 读锁 + go a1.RLockFunc(func(n1 []any) { // 读锁 time.Sleep(2 * time.Second) // 暂停1秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -616,7 +616,7 @@ func TestArray_RLockFunc(t *testing.T) { func TestArray_Json(t *testing.T) { // pointer gtest.C(t, func(t *gtest.T) { - s1 := []interface{}{"a", "b", "d", "c"} + s1 := []any{"a", "b", "d", "c"} a1 := garray.NewArrayFrom(s1) b1, err1 := json.Marshal(a1) b2, err2 := json.Marshal(s1) @@ -635,7 +635,7 @@ func TestArray_Json(t *testing.T) { }) // value. gtest.C(t, func(t *gtest.T) { - s1 := []interface{}{"a", "b", "d", "c"} + s1 := []any{"a", "b", "d", "c"} a1 := *garray.NewArrayFrom(s1) b1, err1 := json.Marshal(a1) b2, err2 := json.Marshal(s1) @@ -696,26 +696,26 @@ func TestArray_Iterator(t *testing.T) { slice := g.Slice{"a", "b", "d", "c"} array := garray.NewArrayFrom(slice) gtest.C(t, func(t *gtest.T) { - array.Iterator(func(k int, v interface{}) bool { + array.Iterator(func(k int, v any) bool { t.Assert(v, slice[k]) return true }) }) gtest.C(t, func(t *gtest.T) { - array.IteratorAsc(func(k int, v interface{}) bool { + array.IteratorAsc(func(k int, v any) bool { t.Assert(v, slice[k]) return true }) }) gtest.C(t, func(t *gtest.T) { - array.IteratorDesc(func(k int, v interface{}) bool { + array.IteratorDesc(func(k int, v any) bool { t.Assert(v, slice[k]) return true }) }) gtest.C(t, func(t *gtest.T) { index := 0 - array.Iterator(func(k int, v interface{}) bool { + array.Iterator(func(k int, v any) bool { index++ return false }) @@ -723,7 +723,7 @@ func TestArray_Iterator(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { index := 0 - array.IteratorAsc(func(k int, v interface{}) bool { + array.IteratorAsc(func(k int, v any) bool { index++ return false }) @@ -731,7 +731,7 @@ func TestArray_Iterator(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { index := 0 - array.IteratorDesc(func(k int, v interface{}) bool { + array.IteratorDesc(func(k int, v any) bool { index++ return false }) @@ -805,27 +805,27 @@ func TestArray_Filter(t *testing.T) { gtest.C(t, func(t *gtest.T) { values := g.Slice{0, 1, 2, 3, 4, "", g.Slice{}} array := garray.NewArrayFromCopy(values) - t.Assert(array.Filter(func(index int, value interface{}) bool { + t.Assert(array.Filter(func(index int, value any) bool { return empty.IsNil(value) }).Slice(), values) }) gtest.C(t, func(t *gtest.T) { array := garray.NewArrayFromCopy(g.Slice{nil, 1, 2, 3, 4, nil}) - t.Assert(array.Filter(func(index int, value interface{}) bool { + t.Assert(array.Filter(func(index int, value any) bool { return empty.IsNil(value) }), g.Slice{1, 2, 3, 4}) }) gtest.C(t, func(t *gtest.T) { array := garray.NewArrayFrom(g.Slice{0, 1, 2, 3, 4, "", g.Slice{}}) - t.Assert(array.Filter(func(index int, value interface{}) bool { + t.Assert(array.Filter(func(index int, value any) bool { return empty.IsEmpty(value) }), g.Slice{1, 2, 3, 4}) }) gtest.C(t, func(t *gtest.T) { array := garray.NewArrayFrom(g.Slice{1, 2, 3, 4}) - t.Assert(array.Filter(func(index int, value interface{}) bool { + t.Assert(array.Filter(func(index int, value any) bool { return empty.IsEmpty(value) }), g.Slice{1, 2, 3, 4}) }) @@ -845,7 +845,7 @@ func TestArray_FilterEmpty(t *testing.T) { func TestArray_Walk(t *testing.T) { gtest.C(t, func(t *gtest.T) { array := garray.NewArrayFrom(g.Slice{"1", "2"}) - t.Assert(array.Walk(func(value interface{}) interface{} { + t.Assert(array.Walk(func(value any) any { return "key-" + gconv.String(value) }), g.Slice{"key-1", "key-2"}) }) diff --git a/container/garray/garray_z_unit_normal_int_test.go b/container/garray/garray_z_unit_normal_int_test.go index d3f0a3d5c29..1c6a09d08dc 100644 --- a/container/garray/garray_z_unit_normal_int_test.go +++ b/container/garray/garray_z_unit_normal_int_test.go @@ -195,7 +195,7 @@ func TestIntArray_Range(t *testing.T) { func TestIntArray_Merge(t *testing.T) { gtest.C(t, func(t *gtest.T) { - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { if gconv.Int(v1) < gconv.Int(v2) { return 0 } @@ -204,7 +204,7 @@ func TestIntArray_Merge(t *testing.T) { n1 := []int{0, 1, 2, 3} n2 := []int{4, 5, 6, 7} - i1 := []interface{}{"1", "2"} + i1 := []any{"1", "2"} s1 := []string{"a", "b", "c"} s2 := []string{"e", "f"} a1 := garray.NewIntArrayFrom(n1) @@ -216,7 +216,7 @@ func TestIntArray_Merge(t *testing.T) { a6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) a7 := garray.NewSortedStrArrayFrom(s1) - a8 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) + a8 := garray.NewSortedArrayFrom([]any{4, 5}, func1) t.Assert(a1.Merge(a2).Slice(), []int{0, 1, 2, 3, 4, 5, 6, 7}) t.Assert(a1.Merge(a3).Len(), 10) diff --git a/container/garray/garray_z_unit_normal_str_test.go b/container/garray/garray_z_unit_normal_str_test.go index 23a43c39b67..fa486a4175a 100644 --- a/container/garray/garray_z_unit_normal_str_test.go +++ b/container/garray/garray_z_unit_normal_str_test.go @@ -235,14 +235,14 @@ func TestStrArray_PopLeftsAndPopRights(t *testing.T) { value2 := []string{"0", "1", "2", "3", "4", "5", "6"} array1 := garray.NewStrArrayFrom(value1) array2 := garray.NewStrArrayFrom(value2) - t.Assert(array1.PopLefts(2), []interface{}{"0", "1"}) - t.Assert(array1.Slice(), []interface{}{"2", "3", "4", "5", "6"}) - t.Assert(array1.PopRights(2), []interface{}{"5", "6"}) - t.Assert(array1.Slice(), []interface{}{"2", "3", "4"}) - t.Assert(array1.PopRights(20), []interface{}{"2", "3", "4"}) - t.Assert(array1.Slice(), []interface{}{}) - t.Assert(array2.PopLefts(20), []interface{}{"0", "1", "2", "3", "4", "5", "6"}) - t.Assert(array2.Slice(), []interface{}{}) + t.Assert(array1.PopLefts(2), []any{"0", "1"}) + t.Assert(array1.Slice(), []any{"2", "3", "4", "5", "6"}) + t.Assert(array1.PopRights(2), []any{"5", "6"}) + t.Assert(array1.Slice(), []any{"2", "3", "4"}) + t.Assert(array1.PopRights(20), []any{"2", "3", "4"}) + t.Assert(array1.Slice(), []any{}) + t.Assert(array2.PopLefts(20), []any{"0", "1", "2", "3", "4", "5", "6"}) + t.Assert(array2.Slice(), []any{}) }) } @@ -251,12 +251,12 @@ func TestString_Range(t *testing.T) { value1 := []string{"0", "1", "2", "3", "4", "5", "6"} array1 := garray.NewStrArrayFrom(value1) array2 := garray.NewStrArrayFrom(value1, true) - t.Assert(array1.Range(0, 1), []interface{}{"0"}) - t.Assert(array1.Range(1, 2), []interface{}{"1"}) - t.Assert(array1.Range(0, 2), []interface{}{"0", "1"}) + t.Assert(array1.Range(0, 1), []any{"0"}) + t.Assert(array1.Range(1, 2), []any{"1"}) + t.Assert(array1.Range(0, 2), []any{"0", "1"}) t.Assert(array1.Range(-1, 10), value1) t.Assert(array1.Range(10, 1), nil) - t.Assert(array2.Range(0, 1), []interface{}{"0"}) + t.Assert(array2.Range(0, 1), []any{"0"}) }) } @@ -268,7 +268,7 @@ func TestStrArray_Merge(t *testing.T) { array2 := garray.NewStrArrayFrom(a21) t.Assert(array1.Merge(array2).Slice(), []string{"0", "1", "2", "3", "4", "5", "6", "7"}) - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { if gconv.Int(v1) < gconv.Int(v2) { return 0 } @@ -278,9 +278,9 @@ func TestStrArray_Merge(t *testing.T) { s1 := []string{"a", "b", "c", "d"} s2 := []string{"e", "f"} i1 := garray.NewIntArrayFrom([]int{1, 2, 3}) - i2 := garray.NewArrayFrom([]interface{}{3}) + i2 := garray.NewArrayFrom([]any{3}) s3 := garray.NewStrArrayFrom([]string{"g", "h"}) - s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) + s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1) s5 := garray.NewSortedStrArrayFrom(s2) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) a1 := garray.NewStrArrayFrom(s1) diff --git a/container/garray/garray_z_unit_sorted_any_test.go b/container/garray/garray_z_unit_sorted_any_test.go index 70cf53dd39e..9d6a80e2480 100644 --- a/container/garray/garray_z_unit_sorted_any_test.go +++ b/container/garray/garray_z_unit_sorted_any_test.go @@ -24,91 +24,91 @@ import ( func TestSortedArray_NewSortedArrayFrom(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "f", "c"} - a2 := []interface{}{"h", "j", "i", "k"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "f", "c"} + a2 := []any{"h", "j", "i", "k"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } - func2 := func(v1, v2 interface{}) int { + func2 := func(v1, v2 any) int { return -1 } array1 := garray.NewSortedArrayFrom(a1, func1) array2 := garray.NewSortedArrayFrom(a2, func2) t.Assert(array1.Len(), 3) - t.Assert(array1, []interface{}{"a", "c", "f"}) + t.Assert(array1, []any{"a", "c", "f"}) t.Assert(array2.Len(), 4) - t.Assert(array2, []interface{}{"k", "i", "j", "h"}) + t.Assert(array2, []any{"k", "i", "j", "h"}) }) } func TestNewSortedArrayFromCopy(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "f", "c"} + a1 := []any{"a", "f", "c"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } - func2 := func(v1, v2 interface{}) int { + func2 := func(v1, v2 any) int { return -1 } array1 := garray.NewSortedArrayFromCopy(a1, func1) array2 := garray.NewSortedArrayFromCopy(a1, func2) t.Assert(array1.Len(), 3) - t.Assert(array1, []interface{}{"a", "c", "f"}) + t.Assert(array1, []any{"a", "c", "f"}) t.Assert(array1.Len(), 3) - t.Assert(array2, []interface{}{"c", "f", "a"}) + t.Assert(array2, []any{"c", "f", "a"}) }) } func TestNewSortedArrayRange(t *testing.T) { gtest.C(t, func(t *gtest.T) { - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return gconv.Int(v1) - gconv.Int(v2) } array1 := garray.NewSortedArrayRange(1, 5, 1, func1) t.Assert(array1.Len(), 5) - t.Assert(array1, []interface{}{1, 2, 3, 4, 5}) + t.Assert(array1, []any{1, 2, 3, 4, 5}) }) } func TestSortedArray_SetArray(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "f", "c"} - a2 := []interface{}{"e", "h", "g", "k"} + a1 := []any{"a", "f", "c"} + a2 := []any{"e", "h", "g", "k"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) array1.SetArray(a2) t.Assert(array1.Len(), 4) - t.Assert(array1, []interface{}{"e", "g", "h", "k"}) + t.Assert(array1, []any{"e", "g", "h", "k"}) }) } func TestSortedArray_Sort(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "f", "c"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "f", "c"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) array1.Sort() t.Assert(array1.Len(), 3) - t.Assert(array1, []interface{}{"a", "c", "f"}) + t.Assert(array1, []any{"a", "c", "f"}) }) } func TestSortedArray_Get(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "f", "c"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "f", "c"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) @@ -129,8 +129,8 @@ func TestSortedArray_Get(t *testing.T) { func TestSortedArray_At(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "f", "c"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "f", "c"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) @@ -141,8 +141,8 @@ func TestSortedArray_At(t *testing.T) { func TestSortedArray_Remove(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "d", "c", "b"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) @@ -178,14 +178,14 @@ func TestSortedArray_Remove(t *testing.T) { func TestSortedArray_PopLeft(t *testing.T) { gtest.C(t, func(t *gtest.T) { array1 := garray.NewSortedArrayFrom( - []interface{}{"a", "d", "c", "b"}, + []any{"a", "d", "c", "b"}, gutil.ComparatorString, ) i1, ok := array1.PopLeft() t.Assert(ok, true) t.Assert(gconv.String(i1), "a") t.Assert(array1.Len(), 3) - t.Assert(array1, []interface{}{"b", "c", "d"}) + t.Assert(array1, []any{"b", "c", "d"}) }) gtest.C(t, func(t *gtest.T) { array := garray.NewSortedArrayFrom(g.Slice{1, 2, 3}, gutil.ComparatorInt) @@ -207,14 +207,14 @@ func TestSortedArray_PopLeft(t *testing.T) { func TestSortedArray_PopRight(t *testing.T) { gtest.C(t, func(t *gtest.T) { array1 := garray.NewSortedArrayFrom( - []interface{}{"a", "d", "c", "b"}, + []any{"a", "d", "c", "b"}, gutil.ComparatorString, ) i1, ok := array1.PopRight() t.Assert(ok, true) t.Assert(gconv.String(i1), "d") t.Assert(array1.Len(), 3) - t.Assert(array1, []interface{}{"a", "b", "c"}) + t.Assert(array1, []any{"a", "b", "c"}) }) gtest.C(t, func(t *gtest.T) { array := garray.NewSortedArrayFrom(g.Slice{1, 2, 3}, gutil.ComparatorInt) @@ -237,14 +237,14 @@ func TestSortedArray_PopRight(t *testing.T) { func TestSortedArray_PopRand(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "d", "c", "b"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) i1, ok := array1.PopRand() t.Assert(ok, true) - t.AssertIN(i1, []interface{}{"a", "d", "c", "b"}) + t.AssertIN(i1, []any{"a", "d", "c", "b"}) t.Assert(array1.Len(), 3) }) @@ -252,19 +252,19 @@ func TestSortedArray_PopRand(t *testing.T) { func TestSortedArray_PopRands(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "d", "c", "b"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) i1 := array1.PopRands(2) t.Assert(len(i1), 2) - t.AssertIN(i1, []interface{}{"a", "d", "c", "b"}) + t.AssertIN(i1, []any{"a", "d", "c", "b"}) t.Assert(array1.Len(), 2) i2 := array1.PopRands(3) t.Assert(len(i1), 2) - t.AssertIN(i2, []interface{}{"a", "d", "c", "b"}) + t.AssertIN(i2, []any{"a", "d", "c", "b"}) t.Assert(array1.Len(), 0) }) @@ -292,33 +292,33 @@ func TestSortedArray_Empty(t *testing.T) { func TestSortedArray_PopLefts(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b", "e", "f"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "d", "c", "b", "e", "f"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) i1 := array1.PopLefts(2) t.Assert(len(i1), 2) - t.AssertIN(i1, []interface{}{"a", "d", "c", "b", "e", "f"}) + t.AssertIN(i1, []any{"a", "d", "c", "b", "e", "f"}) t.Assert(array1.Len(), 4) i2 := array1.PopLefts(5) t.Assert(len(i2), 4) - t.AssertIN(i1, []interface{}{"a", "d", "c", "b", "e", "f"}) + t.AssertIN(i1, []any{"a", "d", "c", "b", "e", "f"}) t.Assert(array1.Len(), 0) }) } func TestSortedArray_PopRights(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b", "e", "f"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "d", "c", "b", "e", "f"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) i1 := array1.PopRights(2) t.Assert(len(i1), 2) - t.Assert(i1, []interface{}{"e", "f"}) + t.Assert(i1, []any{"e", "f"}) t.Assert(array1.Len(), 4) i2 := array1.PopRights(10) @@ -329,36 +329,36 @@ func TestSortedArray_PopRights(t *testing.T) { func TestSortedArray_Range(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b", "e", "f"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "d", "c", "b", "e", "f"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) array2 := garray.NewSortedArrayFrom(a1, func1, true) i1 := array1.Range(2, 5) - t.Assert(i1, []interface{}{"c", "d", "e"}) + t.Assert(i1, []any{"c", "d", "e"}) t.Assert(array1.Len(), 6) i2 := array1.Range(7, 5) t.Assert(len(i2), 0) i2 = array1.Range(-1, 2) - t.Assert(i2, []interface{}{"a", "b"}) + t.Assert(i2, []any{"a", "b"}) i2 = array1.Range(4, 10) t.Assert(len(i2), 2) - t.Assert(i2, []interface{}{"e", "f"}) + t.Assert(i2, []any{"e", "f"}) - t.Assert(array2.Range(1, 3), []interface{}{"b", "c"}) + t.Assert(array2.Range(1, 3), []any{"b", "c"}) }) } func TestSortedArray_Sum(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b", "e", "f"} - a2 := []interface{}{"1", "2", "3", "b", "e", "f"} - a3 := []interface{}{"4", "5", "6"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "d", "c", "b", "e", "f"} + a2 := []any{"1", "2", "3", "b", "e", "f"} + a3 := []any{"4", "5", "6"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) @@ -373,9 +373,9 @@ func TestSortedArray_Sum(t *testing.T) { func TestSortedArray_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b", "e", "f"} + a1 := []any{"a", "d", "c", "b", "e", "f"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) @@ -389,9 +389,9 @@ func TestSortedArray_Clone(t *testing.T) { func TestSortedArray_Clear(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b", "e", "f"} + a1 := []any{"a", "d", "c", "b", "e", "f"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) @@ -404,66 +404,66 @@ func TestSortedArray_Clear(t *testing.T) { func TestSortedArray_Chunk(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b", "e"} + a1 := []any{"a", "d", "c", "b", "e"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) i1 := array1.Chunk(2) t.Assert(len(i1), 3) - t.Assert(i1[0], []interface{}{"a", "b"}) - t.Assert(i1[2], []interface{}{"e"}) + t.Assert(i1[0], []any{"a", "b"}) + t.Assert(i1[2], []any{"e"}) i1 = array1.Chunk(0) t.Assert(len(i1), 0) }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{1, 2, 3, 4, 5} + a1 := []any{1, 2, 3, 4, 5} array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) chunks := array1.Chunk(3) t.Assert(len(chunks), 2) - t.Assert(chunks[0], []interface{}{1, 2, 3}) - t.Assert(chunks[1], []interface{}{4, 5}) + t.Assert(chunks[0], []any{1, 2, 3}) + t.Assert(chunks[1], []any{4, 5}) t.Assert(array1.Chunk(0), nil) }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{1, 2, 3, 4, 5, 6} + a1 := []any{1, 2, 3, 4, 5, 6} array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) chunks := array1.Chunk(2) t.Assert(len(chunks), 3) - t.Assert(chunks[0], []interface{}{1, 2}) - t.Assert(chunks[1], []interface{}{3, 4}) - t.Assert(chunks[2], []interface{}{5, 6}) + t.Assert(chunks[0], []any{1, 2}) + t.Assert(chunks[1], []any{3, 4}) + t.Assert(chunks[2], []any{5, 6}) t.Assert(array1.Chunk(0), nil) }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{1, 2, 3, 4, 5, 6} + a1 := []any{1, 2, 3, 4, 5, 6} array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) chunks := array1.Chunk(3) t.Assert(len(chunks), 2) - t.Assert(chunks[0], []interface{}{1, 2, 3}) - t.Assert(chunks[1], []interface{}{4, 5, 6}) + t.Assert(chunks[0], []any{1, 2, 3}) + t.Assert(chunks[1], []any{4, 5, 6}) t.Assert(array1.Chunk(0), nil) }) } func TestSortedArray_SubSlice(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "b", "e"} + a1 := []any{"a", "d", "c", "b", "e"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) array2 := garray.NewSortedArrayFrom(a1, func1, true) i1 := array1.SubSlice(2, 3) t.Assert(len(i1), 3) - t.Assert(i1, []interface{}{"c", "d", "e"}) + t.Assert(i1, []any{"c", "d", "e"}) i1 = array1.SubSlice(2, 6) t.Assert(len(i1), 3) - t.Assert(i1, []interface{}{"c", "d", "e"}) + t.Assert(i1, []any{"c", "d", "e"}) i1 = array1.SubSlice(7, 2) t.Assert(len(i1), 0) @@ -473,25 +473,25 @@ func TestSortedArray_SubSlice(t *testing.T) { s1 = array1.SubSlice(-9, 2) t.Assert(s1, nil) - t.Assert(array2.SubSlice(1, 3), []interface{}{"b", "c", "d"}) + t.Assert(array2.SubSlice(1, 3), []any{"b", "c", "d"}) }) } func TestSortedArray_Rand(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c"} + a1 := []any{"a", "d", "c"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) i1, ok := array1.Rand() t.Assert(ok, true) - t.AssertIN(i1, []interface{}{"a", "d", "c"}) + t.AssertIN(i1, []any{"a", "d", "c"}) t.Assert(array1.Len(), 3) - array2 := garray.NewSortedArrayFrom([]interface{}{}, func1) + array2 := garray.NewSortedArrayFrom([]any{}, func1) v, ok := array2.Rand() t.Assert(ok, false) t.Assert(v, nil) @@ -500,21 +500,21 @@ func TestSortedArray_Rand(t *testing.T) { func TestSortedArray_Rands(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c"} + a1 := []any{"a", "d", "c"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) i1 := array1.Rands(2) - t.AssertIN(i1, []interface{}{"a", "d", "c"}) + t.AssertIN(i1, []any{"a", "d", "c"}) t.Assert(len(i1), 2) t.Assert(array1.Len(), 3) i1 = array1.Rands(4) t.Assert(len(i1), 4) - array2 := garray.NewSortedArrayFrom([]interface{}{}, func1) + array2 := garray.NewSortedArrayFrom([]any{}, func1) v := array2.Rands(1) t.Assert(v, nil) }) @@ -522,8 +522,8 @@ func TestSortedArray_Rands(t *testing.T) { func TestSortedArray_Join(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c"} - func1 := func(v1, v2 interface{}) int { + a1 := []any{"a", "d", "c"} + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) @@ -532,13 +532,13 @@ func TestSortedArray_Join(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, `"a"`, `\a`} + a1 := []any{0, 1, `"a"`, `\a`} array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorString) t.Assert(array1.Join("."), `"a".0.1.\a`) }) gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{} + a1 := []any{} array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorString) t.Assert(array1.Join("."), "") }) @@ -546,7 +546,7 @@ func TestSortedArray_Join(t *testing.T) { func TestSortedArray_String(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{0, 1, "a", "b"} + a1 := []any{0, 1, "a", "b"} array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorString) t.Assert(array1.String(), `[0,1,"a","b"]`) @@ -557,9 +557,9 @@ func TestSortedArray_String(t *testing.T) { func TestSortedArray_CountValues(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{"a", "d", "c", "c"} + a1 := []any{"a", "d", "c", "c"} - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } array1 := garray.NewSortedArrayFrom(a1, func1) @@ -573,41 +573,41 @@ func TestSortedArray_CountValues(t *testing.T) { func TestSortedArray_SetUnique(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5} + a1 := []any{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5} array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) array1.SetUnique(true) t.Assert(array1.Len(), 5) - t.Assert(array1, []interface{}{1, 2, 3, 4, 5}) + t.Assert(array1, []any{1, 2, 3, 4, 5}) }) } func TestSortedArray_Unique(t *testing.T) { gtest.C(t, func(t *gtest.T) { - a1 := []interface{}{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5} + a1 := []any{1, 2, 3, 4, 5, 3, 2, 2, 3, 5, 5} array1 := garray.NewSortedArrayFrom(a1, gutil.ComparatorInt) array1.Unique() t.Assert(array1.Len(), 5) - t.Assert(array1, []interface{}{1, 2, 3, 4, 5}) + t.Assert(array1, []any{1, 2, 3, 4, 5}) - array2 := garray.NewSortedArrayFrom([]interface{}{}, gutil.ComparatorInt) + array2 := garray.NewSortedArrayFrom([]any{}, gutil.ComparatorInt) array2.Unique() t.Assert(array2.Len(), 0) - t.Assert(array2, []interface{}{}) + t.Assert(array2, []any{}) }) } func TestSortedArray_LockFunc(t *testing.T) { gtest.C(t, func(t *gtest.T) { - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } - s1 := []interface{}{"a", "b", "c", "d"} + s1 := []any{"a", "b", "c", "d"} a1 := garray.NewSortedArrayFrom(s1, func1, true) ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) // go1 - go a1.LockFunc(func(n1 []interface{}) { // 读写锁 + go a1.LockFunc(func(n1 []any) { // 读写锁 time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -633,16 +633,16 @@ func TestSortedArray_LockFunc(t *testing.T) { func TestSortedArray_RLockFunc(t *testing.T) { gtest.C(t, func(t *gtest.T) { - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { return strings.Compare(gconv.String(v1), gconv.String(v2)) } - s1 := []interface{}{"a", "b", "c", "d"} + s1 := []any{"a", "b", "c", "d"} a1 := garray.NewSortedArrayFrom(s1, func1, true) ch1 := make(chan int64, 3) ch2 := make(chan int64, 3) // go1 - go a1.RLockFunc(func(n1 []interface{}) { // 读写锁 + go a1.RLockFunc(func(n1 []any) { // 读写锁 time.Sleep(2 * time.Second) // 暂停2秒 n1[2] = "g" ch2 <- gconv.Int64(time.Now().UnixNano() / 1000 / 1000) @@ -668,19 +668,19 @@ func TestSortedArray_RLockFunc(t *testing.T) { func TestSortedArray_Merge(t *testing.T) { gtest.C(t, func(t *gtest.T) { - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { if gconv.Int(v1) < gconv.Int(v2) { return 0 } return 1 } - s1 := []interface{}{"a", "b", "c", "d"} + s1 := []any{"a", "b", "c", "d"} s2 := []string{"e", "f"} i1 := garray.NewIntArrayFrom([]int{1, 2, 3}) - i2 := garray.NewArrayFrom([]interface{}{3}) + i2 := garray.NewArrayFrom([]any{3}) s3 := garray.NewStrArrayFrom([]string{"g", "h"}) - s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) + s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1) s5 := garray.NewSortedStrArrayFrom(s2) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) @@ -699,8 +699,8 @@ func TestSortedArray_Merge(t *testing.T) { func TestSortedArray_Json(t *testing.T) { // array pointer gtest.C(t, func(t *gtest.T) { - s1 := []interface{}{"a", "b", "d", "c"} - s2 := []interface{}{"a", "b", "c", "d"} + s1 := []any{"a", "b", "d", "c"} + s2 := []any{"a", "b", "c", "d"} a1 := garray.NewSortedArrayFrom(s1, gutil.ComparatorString) b1, err1 := json.Marshal(a1) b2, err2 := json.Marshal(s1) @@ -720,8 +720,8 @@ func TestSortedArray_Json(t *testing.T) { }) // array value gtest.C(t, func(t *gtest.T) { - s1 := []interface{}{"a", "b", "d", "c"} - s2 := []interface{}{"a", "b", "c", "d"} + s1 := []any{"a", "b", "d", "c"} + s2 := []any{"a", "b", "c", "d"} a1 := *garray.NewSortedArrayFrom(s1, gutil.ComparatorString) b1, err1 := json.Marshal(a1) b2, err2 := json.Marshal(s1) @@ -817,26 +817,26 @@ func TestSortedArray_Iterator(t *testing.T) { slice := g.Slice{"a", "b", "d", "c"} array := garray.NewSortedArrayFrom(slice, gutil.ComparatorString) gtest.C(t, func(t *gtest.T) { - array.Iterator(func(k int, v interface{}) bool { + array.Iterator(func(k int, v any) bool { t.Assert(v, slice[k]) return true }) }) gtest.C(t, func(t *gtest.T) { - array.IteratorAsc(func(k int, v interface{}) bool { + array.IteratorAsc(func(k int, v any) bool { t.Assert(v, slice[k]) return true }) }) gtest.C(t, func(t *gtest.T) { - array.IteratorDesc(func(k int, v interface{}) bool { + array.IteratorDesc(func(k int, v any) bool { t.Assert(v, slice[k]) return true }) }) gtest.C(t, func(t *gtest.T) { index := 0 - array.Iterator(func(k int, v interface{}) bool { + array.Iterator(func(k int, v any) bool { index++ return false }) @@ -844,7 +844,7 @@ func TestSortedArray_Iterator(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { index := 0 - array.IteratorAsc(func(k int, v interface{}) bool { + array.IteratorAsc(func(k int, v any) bool { index++ return false }) @@ -852,7 +852,7 @@ func TestSortedArray_Iterator(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { index := 0 - array.IteratorDesc(func(k int, v interface{}) bool { + array.IteratorDesc(func(k int, v any) bool { index++ return false }) @@ -913,25 +913,25 @@ func TestSortedArray_Filter(t *testing.T) { gtest.C(t, func(t *gtest.T) { values := g.Slice{0, 1, 2, 3, 4, "", g.Slice{}} array := garray.NewSortedArrayFromCopy(values, gutil.ComparatorInt) - t.Assert(array.Filter(func(index int, value interface{}) bool { + t.Assert(array.Filter(func(index int, value any) bool { return empty.IsNil(value) }).Slice(), g.Slice{0, "", g.Slice{}, 1, 2, 3, 4}) }) gtest.C(t, func(t *gtest.T) { array := garray.NewSortedArrayFromCopy(g.Slice{nil, 1, 2, 3, 4, nil}, gutil.ComparatorInt) - t.Assert(array.Filter(func(index int, value interface{}) bool { + t.Assert(array.Filter(func(index int, value any) bool { return empty.IsNil(value) }), g.Slice{1, 2, 3, 4}) }) gtest.C(t, func(t *gtest.T) { array := garray.NewSortedArrayFrom(g.Slice{0, 1, 2, 3, 4, "", g.Slice{}}, gutil.ComparatorInt) - t.Assert(array.Filter(func(index int, value interface{}) bool { + t.Assert(array.Filter(func(index int, value any) bool { return empty.IsEmpty(value) }), g.Slice{1, 2, 3, 4}) }) gtest.C(t, func(t *gtest.T) { array := garray.NewSortedArrayFrom(g.Slice{1, 2, 3, 4}, gutil.ComparatorInt) - t.Assert(array.Filter(func(index int, value interface{}) bool { + t.Assert(array.Filter(func(index int, value any) bool { return empty.IsEmpty(value) }), g.Slice{1, 2, 3, 4}) }) @@ -963,7 +963,7 @@ func TestSortedArray_FilterEmpty(t *testing.T) { func TestSortedArray_Walk(t *testing.T) { gtest.C(t, func(t *gtest.T) { array := garray.NewSortedArrayFrom(g.Slice{"1", "2"}, gutil.ComparatorString) - t.Assert(array.Walk(func(value interface{}) interface{} { + t.Assert(array.Walk(func(value any) any { return "key-" + gconv.String(value) }), g.Slice{"key-1", "key-2"}) }) @@ -971,14 +971,14 @@ func TestSortedArray_Walk(t *testing.T) { func TestSortedArray_IsEmpty(t *testing.T) { gtest.C(t, func(t *gtest.T) { - array := garray.NewSortedArrayFrom([]interface{}{}, gutil.ComparatorString) + array := garray.NewSortedArrayFrom([]any{}, gutil.ComparatorString) t.Assert(array.IsEmpty(), true) }) } func TestSortedArray_DeepCopy(t *testing.T) { gtest.C(t, func(t *gtest.T) { - array := garray.NewSortedArrayFrom([]interface{}{1, 2, 3, 4, 5}, gutil.ComparatorString) + array := garray.NewSortedArrayFrom([]any{1, 2, 3, 4, 5}, gutil.ComparatorString) copyArray := array.DeepCopy().(*garray.SortedArray) array.Add(6) copyArray.Add(7) diff --git a/container/garray/garray_z_unit_sorted_int_test.go b/container/garray/garray_z_unit_sorted_int_test.go index a4ebf4fe96e..b218ada96a7 100644 --- a/container/garray/garray_z_unit_sorted_int_test.go +++ b/container/garray/garray_z_unit_sorted_int_test.go @@ -573,7 +573,7 @@ func TestSortedIntArray_RLockFunc(t *testing.T) { func TestSortedIntArray_Merge(t *testing.T) { gtest.C(t, func(t *gtest.T) { - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { if gconv.Int(v1) < gconv.Int(v2) { return 0 } @@ -582,9 +582,9 @@ func TestSortedIntArray_Merge(t *testing.T) { i0 := []int{1, 2, 3, 4} s2 := []string{"e", "f"} i1 := garray.NewIntArrayFrom([]int{1, 2, 3}) - i2 := garray.NewArrayFrom([]interface{}{3}) + i2 := garray.NewArrayFrom([]any{3}) s3 := garray.NewStrArrayFrom([]string{"g", "h"}) - s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) + s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1) s5 := garray.NewSortedStrArrayFrom(s2) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) a1 := garray.NewSortedIntArrayFrom(i0) diff --git a/container/garray/garray_z_unit_sorted_str_test.go b/container/garray/garray_z_unit_sorted_str_test.go index d1fef5c992a..b67d2fe90e5 100644 --- a/container/garray/garray_z_unit_sorted_str_test.go +++ b/container/garray/garray_z_unit_sorted_str_test.go @@ -581,7 +581,7 @@ func TestSortedStrArray_RLockFunc(t *testing.T) { func TestSortedStrArray_Merge(t *testing.T) { gtest.C(t, func(t *gtest.T) { - func1 := func(v1, v2 interface{}) int { + func1 := func(v1, v2 any) int { if gconv.Int(v1) < gconv.Int(v2) { return 0 } @@ -591,9 +591,9 @@ func TestSortedStrArray_Merge(t *testing.T) { s1 := []string{"a", "b", "c", "d"} s2 := []string{"e", "f"} i1 := garray.NewIntArrayFrom([]int{1, 2, 3}) - i2 := garray.NewArrayFrom([]interface{}{3}) + i2 := garray.NewArrayFrom([]any{3}) s3 := garray.NewStrArrayFrom([]string{"g", "h"}) - s4 := garray.NewSortedArrayFrom([]interface{}{4, 5}, func1) + s4 := garray.NewSortedArrayFrom([]any{4, 5}, func1) s5 := garray.NewSortedStrArrayFrom(s2) s6 := garray.NewSortedIntArrayFrom([]int{1, 2, 3}) a1 := garray.NewSortedStrArrayFrom(s1) diff --git a/container/glist/glist.go b/container/glist/glist.go index 9b5424666a3..518284bef15 100644 --- a/container/glist/glist.go +++ b/container/glist/glist.go @@ -41,7 +41,7 @@ func New(safe ...bool) *List { // NewFrom creates and returns a list from a copy of given slice `array`. // The parameter `safe` is used to specify whether using list in concurrent-safety, // which is false in default. -func NewFrom(array []interface{}, safe ...bool) *List { +func NewFrom(array []any, safe ...bool) *List { l := list.New() for _, v := range array { l.PushBack(v) @@ -53,7 +53,7 @@ func NewFrom(array []interface{}, safe ...bool) *List { } // PushFront inserts a new element `e` with value `v` at the front of list `l` and returns `e`. -func (l *List) PushFront(v interface{}) (e *Element) { +func (l *List) PushFront(v any) (e *Element) { l.mu.Lock() if l.list == nil { l.list = list.New() @@ -64,7 +64,7 @@ func (l *List) PushFront(v interface{}) (e *Element) { } // PushBack inserts a new element `e` with value `v` at the back of list `l` and returns `e`. -func (l *List) PushBack(v interface{}) (e *Element) { +func (l *List) PushBack(v any) (e *Element) { l.mu.Lock() if l.list == nil { l.list = list.New() @@ -75,7 +75,7 @@ func (l *List) PushBack(v interface{}) (e *Element) { } // PushFronts inserts multiple new elements with values `values` at the front of list `l`. -func (l *List) PushFronts(values []interface{}) { +func (l *List) PushFronts(values []any) { l.mu.Lock() if l.list == nil { l.list = list.New() @@ -87,7 +87,7 @@ func (l *List) PushFronts(values []interface{}) { } // PushBacks inserts multiple new elements with values `values` at the back of list `l`. -func (l *List) PushBacks(values []interface{}) { +func (l *List) PushBacks(values []any) { l.mu.Lock() if l.list == nil { l.list = list.New() @@ -99,7 +99,7 @@ func (l *List) PushBacks(values []interface{}) { } // PopBack removes the element from back of `l` and returns the value of the element. -func (l *List) PopBack() (value interface{}) { +func (l *List) PopBack() (value any) { l.mu.Lock() defer l.mu.Unlock() if l.list == nil { @@ -113,7 +113,7 @@ func (l *List) PopBack() (value interface{}) { } // PopFront removes the element from front of `l` and returns the value of the element. -func (l *List) PopFront() (value interface{}) { +func (l *List) PopFront() (value any) { l.mu.Lock() defer l.mu.Unlock() if l.list == nil { @@ -128,7 +128,7 @@ func (l *List) PopFront() (value interface{}) { // PopBacks removes `max` elements from back of `l` // and returns values of the removed elements as slice. -func (l *List) PopBacks(max int) (values []interface{}) { +func (l *List) PopBacks(max int) (values []any) { l.mu.Lock() defer l.mu.Unlock() if l.list == nil { @@ -140,7 +140,7 @@ func (l *List) PopBacks(max int) (values []interface{}) { if max > 0 && max < length { length = max } - values = make([]interface{}, length) + values = make([]any, length) for i := 0; i < length; i++ { values[i] = l.list.Remove(l.list.Back()) } @@ -150,7 +150,7 @@ func (l *List) PopBacks(max int) (values []interface{}) { // PopFronts removes `max` elements from front of `l` // and returns values of the removed elements as slice. -func (l *List) PopFronts(max int) (values []interface{}) { +func (l *List) PopFronts(max int) (values []any) { l.mu.Lock() defer l.mu.Unlock() if l.list == nil { @@ -162,7 +162,7 @@ func (l *List) PopFronts(max int) (values []interface{}) { if max > 0 && max < length { length = max } - values = make([]interface{}, length) + values = make([]any, length) for i := 0; i < length; i++ { values[i] = l.list.Remove(l.list.Front()) } @@ -172,18 +172,18 @@ func (l *List) PopFronts(max int) (values []interface{}) { // PopBackAll removes all elements from back of `l` // and returns values of the removed elements as slice. -func (l *List) PopBackAll() []interface{} { +func (l *List) PopBackAll() []any { return l.PopBacks(-1) } // PopFrontAll removes all elements from front of `l` // and returns values of the removed elements as slice. -func (l *List) PopFrontAll() []interface{} { +func (l *List) PopFrontAll() []any { return l.PopFronts(-1) } // FrontAll copies and returns values of all elements from front of `l` as slice. -func (l *List) FrontAll() (values []interface{}) { +func (l *List) FrontAll() (values []any) { l.mu.RLock() defer l.mu.RUnlock() if l.list == nil { @@ -191,7 +191,7 @@ func (l *List) FrontAll() (values []interface{}) { } length := l.list.Len() if length > 0 { - values = make([]interface{}, length) + values = make([]any, length) for i, e := 0, l.list.Front(); i < length; i, e = i+1, e.Next() { values[i] = e.Value } @@ -200,7 +200,7 @@ func (l *List) FrontAll() (values []interface{}) { } // BackAll copies and returns values of all elements from back of `l` as slice. -func (l *List) BackAll() (values []interface{}) { +func (l *List) BackAll() (values []any) { l.mu.RLock() defer l.mu.RUnlock() if l.list == nil { @@ -208,7 +208,7 @@ func (l *List) BackAll() (values []interface{}) { } length := l.list.Len() if length > 0 { - values = make([]interface{}, length) + values = make([]any, length) for i, e := 0, l.list.Back(); i < length; i, e = i+1, e.Prev() { values[i] = e.Value } @@ -217,7 +217,7 @@ func (l *List) BackAll() (values []interface{}) { } // FrontValue returns value of the first element of `l` or nil if the list is empty. -func (l *List) FrontValue() (value interface{}) { +func (l *List) FrontValue() (value any) { l.mu.RLock() defer l.mu.RUnlock() if l.list == nil { @@ -230,7 +230,7 @@ func (l *List) FrontValue() (value interface{}) { } // BackValue returns value of the last element of `l` or nil if the list is empty. -func (l *List) BackValue() (value interface{}) { +func (l *List) BackValue() (value any) { l.mu.RLock() defer l.mu.RUnlock() if l.list == nil { @@ -362,7 +362,7 @@ func (l *List) PushFrontList(other *List) { // InsertAfter inserts a new element `e` with value `v` immediately after `p` and returns `e`. // If `p` is not an element of `l`, the list is not modified. // The `p` must not be nil. -func (l *List) InsertAfter(p *Element, v interface{}) (e *Element) { +func (l *List) InsertAfter(p *Element, v any) (e *Element) { l.mu.Lock() defer l.mu.Unlock() if l.list == nil { @@ -375,7 +375,7 @@ func (l *List) InsertAfter(p *Element, v interface{}) (e *Element) { // InsertBefore inserts a new element `e` with value `v` immediately before `p` and returns `e`. // If `p` is not an element of `l`, the list is not modified. // The `p` must not be nil. -func (l *List) InsertBefore(p *Element, v interface{}) (e *Element) { +func (l *List) InsertBefore(p *Element, v any) (e *Element) { l.mu.Lock() defer l.mu.Unlock() if l.list == nil { @@ -388,7 +388,7 @@ func (l *List) InsertBefore(p *Element, v interface{}) (e *Element) { // Remove removes `e` from `l` if `e` is an element of list `l`. // It returns the element value e.Value. // The element must not be nil. -func (l *List) Remove(e *Element) (value interface{}) { +func (l *List) Remove(e *Element) (value any) { l.mu.Lock() defer l.mu.Unlock() if l.list == nil { @@ -522,7 +522,7 @@ func (l *List) UnmarshalJSON(b []byte) error { if l.list == nil { l.list = list.New() } - var array []interface{} + var array []any if err := json.UnmarshalUseNumber(b, &array); err != nil { return err } @@ -531,13 +531,13 @@ func (l *List) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for list. -func (l *List) UnmarshalValue(value interface{}) (err error) { +func (l *List) UnmarshalValue(value any) (err error) { l.mu.Lock() defer l.mu.Unlock() if l.list == nil { l.list = list.New() } - var array []interface{} + var array []any switch value.(type) { case string, []byte: err = json.UnmarshalUseNumber(gconv.Bytes(value), &array) @@ -549,7 +549,7 @@ func (l *List) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (l *List) DeepCopy() interface{} { +func (l *List) DeepCopy() any { if l == nil { return nil } @@ -562,7 +562,7 @@ func (l *List) DeepCopy() interface{} { } var ( length = l.list.Len() - values = make([]interface{}, length) + values = make([]any, length) ) if length > 0 { for i, e := 0, l.list.Front(); i < length; i, e = i+1, e.Next() { diff --git a/container/glist/glist_z_unit_test.go b/container/glist/glist_z_unit_test.go index d530f097341..d1cb0cd8c71 100644 --- a/container/glist/glist_z_unit_test.go +++ b/container/glist/glist_z_unit_test.go @@ -198,7 +198,7 @@ func TestList(t *testing.T) { }) } -func checkList(t *gtest.T, l *List, es []interface{}) { +func checkList(t *gtest.T, l *List, es []any) { if !checkListLen(t, l, len(es)) { return } @@ -244,36 +244,36 @@ func TestExtending(t *testing.T) { l3 := New() l3.PushBackList(l1) - checkList(t, l3, []interface{}{1, 2, 3}) + checkList(t, l3, []any{1, 2, 3}) l3.PushBackList(l2) - checkList(t, l3, []interface{}{1, 2, 3, 4, 5}) + checkList(t, l3, []any{1, 2, 3, 4, 5}) l3 = New() l3.PushFrontList(l2) - checkList(t, l3, []interface{}{4, 5}) + checkList(t, l3, []any{4, 5}) l3.PushFrontList(l1) - checkList(t, l3, []interface{}{1, 2, 3, 4, 5}) + checkList(t, l3, []any{1, 2, 3, 4, 5}) - checkList(t, l1, []interface{}{1, 2, 3}) - checkList(t, l2, []interface{}{4, 5}) + checkList(t, l1, []any{1, 2, 3}) + checkList(t, l2, []any{4, 5}) l3 = New() l3.PushBackList(l1) - checkList(t, l3, []interface{}{1, 2, 3}) + checkList(t, l3, []any{1, 2, 3}) l3.PushBackList(l3) - checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3}) + checkList(t, l3, []any{1, 2, 3, 1, 2, 3}) l3 = New() l3.PushFrontList(l1) - checkList(t, l3, []interface{}{1, 2, 3}) + checkList(t, l3, []any{1, 2, 3}) l3.PushFrontList(l3) - checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3}) + checkList(t, l3, []any{1, 2, 3, 1, 2, 3}) l3 = New() l1.PushBackList(l3) - checkList(t, l1, []interface{}{1, 2, 3}) + checkList(t, l1, []any{1, 2, 3}) l1.PushFrontList(l3) - checkList(t, l1, []interface{}{1, 2, 3}) + checkList(t, l1, []any{1, 2, 3}) }) } @@ -371,19 +371,19 @@ func TestZeroList(t *testing.T) { gtest.C(t, func(t *gtest.T) { var l1 = New() l1.PushFront(1) - checkList(t, l1, []interface{}{1}) + checkList(t, l1, []any{1}) var l2 = New() l2.PushBack(1) - checkList(t, l2, []interface{}{1}) + checkList(t, l2, []any{1}) var l3 = New() l3.PushFrontList(l1) - checkList(t, l3, []interface{}{1}) + checkList(t, l3, []any{1}) var l4 = New() l4.PushBackList(l2) - checkList(t, l4, []interface{}{1}) + checkList(t, l4, []any{1}) }) } @@ -395,7 +395,7 @@ func TestInsertBeforeUnknownMark(t *testing.T) { l.PushBack(2) l.PushBack(3) l.InsertBefore(new(Element), 1) - checkList(t, l, []interface{}{1, 2, 3}) + checkList(t, l, []any{1, 2, 3}) }) } @@ -407,7 +407,7 @@ func TestInsertAfterUnknownMark(t *testing.T) { l.PushBack(2) l.PushBack(3) l.InsertAfter(new(Element), 1) - checkList(t, l, []interface{}{1, 2, 3}) + checkList(t, l, []any{1, 2, 3}) }) } @@ -421,12 +421,12 @@ func TestMoveUnknownMark(t *testing.T) { e2 := l2.PushBack(2) l1.MoveAfter(e1, e2) - checkList(t, l1, []interface{}{1}) - checkList(t, l2, []interface{}{2}) + checkList(t, l1, []any{1}) + checkList(t, l2, []any{2}) l1.MoveBefore(e1, e2) - checkList(t, l1, []interface{}{1}) - checkList(t, l2, []interface{}{2}) + checkList(t, l1, []any{1}) + checkList(t, l2, []any{2}) }) } @@ -435,58 +435,58 @@ func TestList_RemoveAll(t *testing.T) { l := New() l.PushBack(1) l.RemoveAll() - checkList(t, l, []interface{}{}) + checkList(t, l, []any{}) l.PushBack(2) - checkList(t, l, []interface{}{2}) + checkList(t, l, []any{2}) }) } func TestList_PushFronts(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2} + a1 := []any{1, 2} l.PushFronts(a1) - checkList(t, l, []interface{}{2, 1}) - a1 = []interface{}{3, 4, 5} + checkList(t, l, []any{2, 1}) + a1 = []any{3, 4, 5} l.PushFronts(a1) - checkList(t, l, []interface{}{5, 4, 3, 2, 1}) + checkList(t, l, []any{5, 4, 3, 2, 1}) }) } func TestList_PushBacks(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2} + a1 := []any{1, 2} l.PushBacks(a1) - checkList(t, l, []interface{}{1, 2}) - a1 = []interface{}{3, 4, 5} + checkList(t, l, []any{1, 2}) + a1 = []any{3, 4, 5} l.PushBacks(a1) - checkList(t, l, []interface{}{1, 2, 3, 4, 5}) + checkList(t, l, []any{1, 2, 3, 4, 5}) }) } func TestList_PopBacks(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} - a2 := []interface{}{"a", "c", "b", "e"} + a1 := []any{1, 2, 3, 4} + a2 := []any{"a", "c", "b", "e"} l.PushFronts(a1) i1 := l.PopBacks(2) - t.Assert(i1, []interface{}{1, 2}) + t.Assert(i1, []any{1, 2}) l.PushBacks(a2) // 4.3,a,c,b,e i1 = l.PopBacks(3) - t.Assert(i1, []interface{}{"e", "b", "c"}) + t.Assert(i1, []any{"e", "b", "c"}) }) } func TestList_PopFronts(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) i1 := l.PopFronts(2) - t.Assert(i1, []interface{}{4, 3}) + t.Assert(i1, []any{4, 3}) t.Assert(l.Len(), 2) }) } @@ -494,10 +494,10 @@ func TestList_PopFronts(t *testing.T) { func TestList_PopBackAll(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) i1 := l.PopBackAll() - t.Assert(i1, []interface{}{1, 2, 3, 4}) + t.Assert(i1, []any{1, 2, 3, 4}) t.Assert(l.Len(), 0) }) } @@ -505,10 +505,10 @@ func TestList_PopBackAll(t *testing.T) { func TestList_PopFrontAll(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) i1 := l.PopFrontAll() - t.Assert(i1, []interface{}{4, 3, 2, 1}) + t.Assert(i1, []any{4, 3, 2, 1}) t.Assert(l.Len(), 0) }) } @@ -516,10 +516,10 @@ func TestList_PopFrontAll(t *testing.T) { func TestList_FrontAll(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) i1 := l.FrontAll() - t.Assert(i1, []interface{}{4, 3, 2, 1}) + t.Assert(i1, []any{4, 3, 2, 1}) t.Assert(l.Len(), 4) }) } @@ -527,10 +527,10 @@ func TestList_FrontAll(t *testing.T) { func TestList_BackAll(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) i1 := l.BackAll() - t.Assert(i1, []interface{}{1, 2, 3, 4}) + t.Assert(i1, []any{1, 2, 3, 4}) t.Assert(l.Len(), 4) }) } @@ -539,7 +539,7 @@ func TestList_FrontValue(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() l2 := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) i1 := l.FrontValue() t.Assert(gconv.Int(i1), 4) @@ -554,7 +554,7 @@ func TestList_BackValue(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() l2 := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) i1 := l.BackValue() t.Assert(gconv.Int(i1), 1) @@ -568,7 +568,7 @@ func TestList_BackValue(t *testing.T) { func TestList_Back(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) e1 := l.Back() t.Assert(e1.Value, 1) @@ -579,7 +579,7 @@ func TestList_Back(t *testing.T) { func TestList_Size(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) t.Assert(l.Size(), 4) l.PopFront() @@ -590,7 +590,7 @@ func TestList_Size(t *testing.T) { func TestList_Removes(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) e1 := l.Back() l.Removes([]*Element{e1}) @@ -599,25 +599,25 @@ func TestList_Removes(t *testing.T) { e2 := l.Back() l.Removes([]*Element{e2}) t.Assert(l.Len(), 2) - checkList(t, l, []interface{}{4, 3}) + checkList(t, l, []any{4, 3}) }) } func TestList_Pop(t *testing.T) { gtest.C(t, func(t *gtest.T) { - l := NewFrom([]interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9}) + l := NewFrom([]any{1, 2, 3, 4, 5, 6, 7, 8, 9}) t.Assert(l.PopBack(), 9) - t.Assert(l.PopBacks(2), []interface{}{8, 7}) + t.Assert(l.PopBacks(2), []any{8, 7}) t.Assert(l.PopFront(), 1) - t.Assert(l.PopFronts(2), []interface{}{2, 3}) + t.Assert(l.PopFronts(2), []any{2, 3}) }) } func TestList_Clear(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) l.Clear() t.Assert(l.Len(), 0) @@ -627,22 +627,22 @@ func TestList_Clear(t *testing.T) { func TestList_IteratorAsc(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 5, 6, 3, 4} + a1 := []any{1, 2, 5, 6, 3, 4} l.PushFronts(a1) e1 := l.Back() fun1 := func(e *Element) bool { return gconv.Int(e1.Value) > 2 } - checkList(t, l, []interface{}{4, 3, 6, 5, 2, 1}) + checkList(t, l, []any{4, 3, 6, 5, 2, 1}) l.IteratorAsc(fun1) - checkList(t, l, []interface{}{4, 3, 6, 5, 2, 1}) + checkList(t, l, []any{4, 3, 6, 5, 2, 1}) }) } func TestList_IteratorDesc(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{1, 2, 3, 4} + a1 := []any{1, 2, 3, 4} l.PushFronts(a1) e1 := l.Back() fun1 := func(e *Element) bool { @@ -650,28 +650,28 @@ func TestList_IteratorDesc(t *testing.T) { } l.IteratorDesc(fun1) t.Assert(l.Len(), 4) - checkList(t, l, []interface{}{4, 3, 2, 1}) + checkList(t, l, []any{4, 3, 2, 1}) }) } func TestList_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - a1 := []interface{}{"a", "b", "c", "d", "e"} + a1 := []any{"a", "b", "c", "d", "e"} l.PushFronts(a1) e1 := l.Back() fun1 := func(e *Element) bool { return gconv.String(e1.Value) > "c" } - checkList(t, l, []interface{}{"e", "d", "c", "b", "a"}) + checkList(t, l, []any{"e", "d", "c", "b", "a"}) l.Iterator(fun1) - checkList(t, l, []interface{}{"e", "d", "c", "b", "a"}) + checkList(t, l, []any{"e", "d", "c", "b", "a"}) }) } func TestList_Join(t *testing.T) { gtest.C(t, func(t *gtest.T) { - l := NewFrom([]interface{}{1, 2, "a", `"b"`, `\c`}) + l := NewFrom([]any{1, 2, "a", `"b"`, `\c`}) t.Assert(l.Join(","), `1,2,a,"b",\c`) t.Assert(l.Join("."), `1.2.a."b".\c`) }) @@ -679,7 +679,7 @@ func TestList_Join(t *testing.T) { func TestList_String(t *testing.T) { gtest.C(t, func(t *gtest.T) { - l := NewFrom([]interface{}{1, 2, "a", `"b"`, `\c`}) + l := NewFrom([]any{1, 2, "a", `"b"`, `\c`}) t.Assert(l.String(), `[1,2,a,"b",\c]`) }) } @@ -687,7 +687,7 @@ func TestList_String(t *testing.T) { func TestList_Json(t *testing.T) { // Marshal gtest.C(t, func(t *gtest.T) { - a := []interface{}{"a", "b", "c"} + a := []any{"a", "b", "c"} l := New() l.PushBacks(a) b1, err1 := json.Marshal(l) @@ -697,7 +697,7 @@ func TestList_Json(t *testing.T) { }) // Unmarshal gtest.C(t, func(t *gtest.T) { - a := []interface{}{"a", "b", "c"} + a := []any{"a", "b", "c"} l := New() b, err := json.Marshal(a) t.AssertNil(err) @@ -708,7 +708,7 @@ func TestList_Json(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { var l List - a := []interface{}{"a", "b", "c"} + a := []any{"a", "b", "c"} b, err := json.Marshal(a) t.AssertNil(err) @@ -726,30 +726,30 @@ func TestList_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var tlist *TList - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "list": []byte(`[1,2,3]`), }, &tlist) t.AssertNil(err) t.Assert(tlist.Name, "john") - t.Assert(tlist.List.FrontAll(), []interface{}{1, 2, 3}) + t.Assert(tlist.List.FrontAll(), []any{1, 2, 3}) }) // Map gtest.C(t, func(t *gtest.T) { var tlist *TList - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", - "list": []interface{}{1, 2, 3}, + "list": []any{1, 2, 3}, }, &tlist) t.AssertNil(err) t.Assert(tlist.Name, "john") - t.Assert(tlist.List.FrontAll(), []interface{}{1, 2, 3}) + t.Assert(tlist.List.FrontAll(), []any{1, 2, 3}) }) } func TestList_DeepCopy(t *testing.T) { gtest.C(t, func(t *gtest.T) { - l := NewFrom([]interface{}{1, 2, "a", `"b"`, `\c`}) + l := NewFrom([]any{1, 2, "a", `"b"`, `\c`}) copyList := l.DeepCopy() cl := copyList.(*List) cl.PopBack() diff --git a/container/gmap/gmap.go b/container/gmap/gmap.go index 4cff99d3a87..04efeb502de 100644 --- a/container/gmap/gmap.go +++ b/container/gmap/gmap.go @@ -24,7 +24,7 @@ func New(safe ...bool) *Map { // there might be some concurrent-safe issues when changing the map outside. // The parameter `safe` is used to specify whether using tree in concurrent-safety, // which is false in default. -func NewFrom(data map[interface{}]interface{}, safe ...bool) *Map { +func NewFrom(data map[any]any, safe ...bool) *Map { return NewAnyAnyMapFrom(data, safe...) } @@ -40,6 +40,6 @@ func NewHashMap(safe ...bool) *Map { // there might be some concurrent-safe issues when changing the map outside. // The parameter `safe` is used to specify whether using tree in concurrent-safety, // which is false in default. -func NewHashMapFrom(data map[interface{}]interface{}, safe ...bool) *Map { +func NewHashMapFrom(data map[any]any, safe ...bool) *Map { return NewAnyAnyMapFrom(data, safe...) } diff --git a/container/gmap/gmap_hash_any_any_map.go b/container/gmap/gmap_hash_any_any_map.go index 1cf02d139e0..1a248bccb51 100644 --- a/container/gmap/gmap_hash_any_any_map.go +++ b/container/gmap/gmap_hash_any_any_map.go @@ -17,10 +17,10 @@ import ( "github.com/gogf/gf/v2/util/gconv" ) -// AnyAnyMap wraps map type `map[interface{}]interface{}` and provides more map features. +// AnyAnyMap wraps map type `map[any]any` and provides more map features. type AnyAnyMap struct { mu rwmutex.RWMutex - data map[interface{}]interface{} + data map[any]any } // NewAnyAnyMap creates and returns an empty hash map. @@ -29,14 +29,14 @@ type AnyAnyMap struct { func NewAnyAnyMap(safe ...bool) *AnyAnyMap { return &AnyAnyMap{ mu: rwmutex.Create(safe...), - data: make(map[interface{}]interface{}), + data: make(map[any]any), } } // NewAnyAnyMapFrom creates and returns a hash map from given map `data`. // Note that, the param `data` map will be set as the underlying data map(no deep copy), // there might be some concurrent-safe issues when changing the map outside. -func NewAnyAnyMapFrom(data map[interface{}]interface{}, safe ...bool) *AnyAnyMap { +func NewAnyAnyMapFrom(data map[any]any, safe ...bool) *AnyAnyMap { return &AnyAnyMap{ mu: rwmutex.Create(safe...), data: data, @@ -45,7 +45,7 @@ func NewAnyAnyMapFrom(data map[interface{}]interface{}, safe ...bool) *AnyAnyMap // Iterator iterates the hash map readonly with custom callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. -func (m *AnyAnyMap) Iterator(f func(k interface{}, v interface{}) bool) { +func (m *AnyAnyMap) Iterator(f func(k any, v any) bool) { for k, v := range m.Map() { if !f(k, v) { break @@ -61,13 +61,13 @@ func (m *AnyAnyMap) Clone(safe ...bool) *AnyAnyMap { // Map returns the underlying data map. // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // or else a pointer to the underlying data. -func (m *AnyAnyMap) Map() map[interface{}]interface{} { +func (m *AnyAnyMap) Map() map[any]any { m.mu.RLock() defer m.mu.RUnlock() if !m.mu.IsSafe() { return m.data } - data := make(map[interface{}]interface{}, len(m.data)) + data := make(map[any]any, len(m.data)) for k, v := range m.data { data[k] = v } @@ -75,21 +75,21 @@ func (m *AnyAnyMap) Map() map[interface{}]interface{} { } // MapCopy returns a shallow copy of the underlying data of the hash map. -func (m *AnyAnyMap) MapCopy() map[interface{}]interface{} { +func (m *AnyAnyMap) MapCopy() map[any]any { m.mu.RLock() defer m.mu.RUnlock() - data := make(map[interface{}]interface{}, len(m.data)) + data := make(map[any]any, len(m.data)) for k, v := range m.data { data[k] = v } return data } -// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. -func (m *AnyAnyMap) MapStrAny() map[string]interface{} { +// MapStrAny returns a copy of the underlying data of the map as map[string]any. +func (m *AnyAnyMap) MapStrAny() map[string]any { m.mu.RLock() defer m.mu.RUnlock() - data := make(map[string]interface{}, len(m.data)) + data := make(map[string]any, len(m.data)) for k, v := range m.data { data[gconv.String(k)] = v } @@ -120,17 +120,17 @@ func (m *AnyAnyMap) FilterNil() { } // Set sets key-value to the hash map. -func (m *AnyAnyMap) Set(key interface{}, value interface{}) { +func (m *AnyAnyMap) Set(key any, value any) { m.mu.Lock() if m.data == nil { - m.data = make(map[interface{}]interface{}) + m.data = make(map[any]any) } m.data[key] = value m.mu.Unlock() } // Sets batch sets key-values to the hash map. -func (m *AnyAnyMap) Sets(data map[interface{}]interface{}) { +func (m *AnyAnyMap) Sets(data map[any]any) { m.mu.Lock() if m.data == nil { m.data = data @@ -144,7 +144,7 @@ func (m *AnyAnyMap) Sets(data map[interface{}]interface{}) { // Search searches the map with given `key`. // Second return parameter `found` is true if key was found, otherwise false. -func (m *AnyAnyMap) Search(key interface{}) (value interface{}, found bool) { +func (m *AnyAnyMap) Search(key any) (value any, found bool) { m.mu.RLock() if m.data != nil { value, found = m.data[key] @@ -154,7 +154,7 @@ func (m *AnyAnyMap) Search(key interface{}) (value interface{}, found bool) { } // Get returns the value by given `key`. -func (m *AnyAnyMap) Get(key interface{}) (value interface{}) { +func (m *AnyAnyMap) Get(key any) (value any) { m.mu.RLock() if m.data != nil { value = m.data[key] @@ -164,7 +164,7 @@ func (m *AnyAnyMap) Get(key interface{}) (value interface{}) { } // Pop retrieves and deletes an item from the map. -func (m *AnyAnyMap) Pop() (key, value interface{}) { +func (m *AnyAnyMap) Pop() (key, value any) { m.mu.Lock() defer m.mu.Unlock() for key, value = range m.data { @@ -176,7 +176,7 @@ func (m *AnyAnyMap) Pop() (key, value interface{}) { // Pops retrieves and deletes `size` items from the map. // It returns all items if size == -1. -func (m *AnyAnyMap) Pops(size int) map[interface{}]interface{} { +func (m *AnyAnyMap) Pops(size int) map[any]any { m.mu.Lock() defer m.mu.Unlock() if size > len(m.data) || size == -1 { @@ -187,7 +187,7 @@ func (m *AnyAnyMap) Pops(size int) map[interface{}]interface{} { } var ( index = 0 - newMap = make(map[interface{}]interface{}, size) + newMap = make(map[any]any, size) ) for k, v := range m.data { delete(m.data, k) @@ -209,16 +209,16 @@ func (m *AnyAnyMap) Pops(size int) map[interface{}]interface{} { // and its return value will be set to the map with `key`. // // It returns value with given `key`. -func (m *AnyAnyMap) doSetWithLockCheck(key interface{}, value interface{}) interface{} { +func (m *AnyAnyMap) doSetWithLockCheck(key any, value any) any { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[interface{}]interface{}) + m.data = make(map[any]any) } if v, ok := m.data[key]; ok { return v } - if f, ok := value.(func() interface{}); ok { + if f, ok := value.(func() any); ok { value = f() } if value != nil { @@ -229,7 +229,7 @@ func (m *AnyAnyMap) doSetWithLockCheck(key interface{}, value interface{}) inter // GetOrSet returns the value by key, // or sets value with given `value` if it does not exist and then returns this value. -func (m *AnyAnyMap) GetOrSet(key interface{}, value interface{}) interface{} { +func (m *AnyAnyMap) GetOrSet(key any, value any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, value) } else { @@ -240,7 +240,7 @@ func (m *AnyAnyMap) GetOrSet(key interface{}, value interface{}) interface{} { // GetOrSetFunc returns the value by key, // or sets value with returned value of callback function `f` if it does not exist // and then returns this value. -func (m *AnyAnyMap) GetOrSetFunc(key interface{}, f func() interface{}) interface{} { +func (m *AnyAnyMap) GetOrSetFunc(key any, f func() any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, f()) } else { @@ -254,7 +254,7 @@ func (m *AnyAnyMap) GetOrSetFunc(key interface{}, f func() interface{}) interfac // // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` // with mutex.Lock of the hash map. -func (m *AnyAnyMap) GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} { +func (m *AnyAnyMap) GetOrSetFuncLock(key any, f func() any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, f) } else { @@ -264,31 +264,31 @@ func (m *AnyAnyMap) GetOrSetFuncLock(key interface{}, f func() interface{}) inte // GetVar returns a Var with the value by given `key`. // The returned Var is un-concurrent safe. -func (m *AnyAnyMap) GetVar(key interface{}) *gvar.Var { +func (m *AnyAnyMap) GetVar(key any) *gvar.Var { return gvar.New(m.Get(key)) } // 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 { +func (m *AnyAnyMap) GetVarOrSet(key any, value any) *gvar.Var { return gvar.New(m.GetOrSet(key, value)) } // GetVarOrSetFunc returns a Var with result from GetOrSetFunc. // The returned Var is un-concurrent safe. -func (m *AnyAnyMap) GetVarOrSetFunc(key interface{}, f func() interface{}) *gvar.Var { +func (m *AnyAnyMap) GetVarOrSetFunc(key any, f func() any) *gvar.Var { return gvar.New(m.GetOrSetFunc(key, f)) } // GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock. // The returned Var is un-concurrent safe. -func (m *AnyAnyMap) GetVarOrSetFuncLock(key interface{}, f func() interface{}) *gvar.Var { +func (m *AnyAnyMap) GetVarOrSetFuncLock(key any, f func() any) *gvar.Var { return gvar.New(m.GetOrSetFuncLock(key, f)) } // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true. // It returns false if `key` exists, and `value` would be ignored. -func (m *AnyAnyMap) SetIfNotExist(key interface{}, value interface{}) bool { +func (m *AnyAnyMap) SetIfNotExist(key any, value any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, value) return true @@ -298,7 +298,7 @@ func (m *AnyAnyMap) SetIfNotExist(key interface{}, value interface{}) bool { // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true. // It returns false if `key` exists, and `value` would be ignored. -func (m *AnyAnyMap) SetIfNotExistFunc(key interface{}, f func() interface{}) bool { +func (m *AnyAnyMap) SetIfNotExistFunc(key any, f func() any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, f()) return true @@ -311,7 +311,7 @@ func (m *AnyAnyMap) SetIfNotExistFunc(key interface{}, f func() interface{}) boo // // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that // it executes function `f` with mutex.Lock of the hash map. -func (m *AnyAnyMap) SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool { +func (m *AnyAnyMap) SetIfNotExistFuncLock(key any, f func() any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, f) return true @@ -320,7 +320,7 @@ func (m *AnyAnyMap) SetIfNotExistFuncLock(key interface{}, f func() interface{}) } // Remove deletes value from map by given `key`, and return this deleted value. -func (m *AnyAnyMap) Remove(key interface{}) (value interface{}) { +func (m *AnyAnyMap) Remove(key any) (value any) { m.mu.Lock() if m.data != nil { var ok bool @@ -333,7 +333,7 @@ func (m *AnyAnyMap) Remove(key interface{}) (value interface{}) { } // Removes batch deletes values of the map by keys. -func (m *AnyAnyMap) Removes(keys []interface{}) { +func (m *AnyAnyMap) Removes(keys []any) { m.mu.Lock() if m.data != nil { for _, key := range keys { @@ -344,11 +344,11 @@ func (m *AnyAnyMap) Removes(keys []interface{}) { } // Keys returns all keys of the map as a slice. -func (m *AnyAnyMap) Keys() []interface{} { +func (m *AnyAnyMap) Keys() []any { m.mu.RLock() defer m.mu.RUnlock() var ( - keys = make([]interface{}, len(m.data)) + keys = make([]any, len(m.data)) index = 0 ) for key := range m.data { @@ -359,11 +359,11 @@ func (m *AnyAnyMap) Keys() []interface{} { } // Values returns all values of the map as a slice. -func (m *AnyAnyMap) Values() []interface{} { +func (m *AnyAnyMap) Values() []any { m.mu.RLock() defer m.mu.RUnlock() var ( - values = make([]interface{}, len(m.data)) + values = make([]any, len(m.data)) index = 0 ) for _, value := range m.data { @@ -375,7 +375,7 @@ func (m *AnyAnyMap) Values() []interface{} { // Contains checks whether a key exists. // It returns true if the `key` exists, or else false. -func (m *AnyAnyMap) Contains(key interface{}) bool { +func (m *AnyAnyMap) Contains(key any) bool { var ok bool m.mu.RLock() if m.data != nil { @@ -402,26 +402,26 @@ func (m *AnyAnyMap) IsEmpty() bool { // Clear deletes all data of the map, it will remake a new underlying data map. func (m *AnyAnyMap) Clear() { m.mu.Lock() - m.data = make(map[interface{}]interface{}) + m.data = make(map[any]any) m.mu.Unlock() } // Replace the data of the map with given `data`. -func (m *AnyAnyMap) Replace(data map[interface{}]interface{}) { +func (m *AnyAnyMap) Replace(data map[any]any) { m.mu.Lock() m.data = data m.mu.Unlock() } // LockFunc locks writing with given callback function `f` within RWMutex.Lock. -func (m *AnyAnyMap) LockFunc(f func(m map[interface{}]interface{})) { +func (m *AnyAnyMap) LockFunc(f func(m map[any]any)) { m.mu.Lock() defer m.mu.Unlock() f(m.data) } // RLockFunc locks reading with given callback function `f` within RWMutex.RLock. -func (m *AnyAnyMap) RLockFunc(f func(m map[interface{}]interface{})) { +func (m *AnyAnyMap) RLockFunc(f func(m map[any]any)) { m.mu.RLock() defer m.mu.RUnlock() f(m.data) @@ -431,7 +431,7 @@ func (m *AnyAnyMap) RLockFunc(f func(m map[interface{}]interface{})) { func (m *AnyAnyMap) Flip() { m.mu.Lock() defer m.mu.Unlock() - n := make(map[interface{}]interface{}, len(m.data)) + n := make(map[any]any, len(m.data)) for k, v := range m.data { n[v] = k } @@ -475,9 +475,9 @@ func (m *AnyAnyMap) UnmarshalJSON(b []byte) error { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[interface{}]interface{}) + m.data = make(map[any]any) } - var data map[string]interface{} + var data map[string]any if err := json.UnmarshalUseNumber(b, &data); err != nil { return err } @@ -488,11 +488,11 @@ func (m *AnyAnyMap) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for map. -func (m *AnyAnyMap) UnmarshalValue(value interface{}) (err error) { +func (m *AnyAnyMap) UnmarshalValue(value any) (err error) { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[interface{}]interface{}) + m.data = make(map[any]any) } for k, v := range gconv.Map(value) { m.data[k] = v @@ -501,14 +501,14 @@ func (m *AnyAnyMap) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (m *AnyAnyMap) DeepCopy() interface{} { +func (m *AnyAnyMap) DeepCopy() any { if m == nil { return nil } m.mu.RLock() defer m.mu.RUnlock() - data := make(map[interface{}]interface{}, len(m.data)) + data := make(map[any]any, len(m.data)) for k, v := range m.data { data[k] = deepcopy.Copy(v) } @@ -540,7 +540,7 @@ func (m *AnyAnyMap) IsSubOf(other *AnyAnyMap) bool { // The returned `addedKeys` are the keys that are in map `m` but not in map `other`. // The returned `removedKeys` are the keys that are in map `other` but not in map `m`. // The returned `updatedKeys` are the keys that are both in map `m` and `other` but their values and not equal (`!=`). -func (m *AnyAnyMap) Diff(other *AnyAnyMap) (addedKeys, removedKeys, updatedKeys []interface{}) { +func (m *AnyAnyMap) Diff(other *AnyAnyMap) (addedKeys, removedKeys, updatedKeys []any) { m.mu.RLock() defer m.mu.RUnlock() other.mu.RLock() diff --git a/container/gmap/gmap_hash_int_any_map.go b/container/gmap/gmap_hash_int_any_map.go index b2d43eca7b4..da4376a9dbd 100644 --- a/container/gmap/gmap_hash_int_any_map.go +++ b/container/gmap/gmap_hash_int_any_map.go @@ -18,10 +18,10 @@ import ( "github.com/gogf/gf/v2/util/gconv" ) -// IntAnyMap implements map[int]interface{} with RWMutex that has switch. +// IntAnyMap implements map[int]any with RWMutex that has switch. type IntAnyMap struct { mu rwmutex.RWMutex - data map[int]interface{} + data map[int]any } // NewIntAnyMap returns an empty IntAnyMap object. @@ -30,14 +30,14 @@ type IntAnyMap struct { func NewIntAnyMap(safe ...bool) *IntAnyMap { return &IntAnyMap{ mu: rwmutex.Create(safe...), - data: make(map[int]interface{}), + data: make(map[int]any), } } // NewIntAnyMapFrom creates and returns a hash map from given map `data`. // Note that, the param `data` map will be set as the underlying data map(no deep copy), // there might be some concurrent-safe issues when changing the map outside. -func NewIntAnyMapFrom(data map[int]interface{}, safe ...bool) *IntAnyMap { +func NewIntAnyMapFrom(data map[int]any, safe ...bool) *IntAnyMap { return &IntAnyMap{ mu: rwmutex.Create(safe...), data: data, @@ -46,7 +46,7 @@ func NewIntAnyMapFrom(data map[int]interface{}, safe ...bool) *IntAnyMap { // Iterator iterates the hash map readonly with custom callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. -func (m *IntAnyMap) Iterator(f func(k int, v interface{}) bool) { +func (m *IntAnyMap) Iterator(f func(k int, v any) bool) { for k, v := range m.Map() { if !f(k, v) { break @@ -62,23 +62,23 @@ func (m *IntAnyMap) Clone() *IntAnyMap { // Map returns the underlying data map. // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // or else a pointer to the underlying data. -func (m *IntAnyMap) Map() map[int]interface{} { +func (m *IntAnyMap) Map() map[int]any { m.mu.RLock() defer m.mu.RUnlock() if !m.mu.IsSafe() { return m.data } - data := make(map[int]interface{}, len(m.data)) + data := make(map[int]any, len(m.data)) for k, v := range m.data { data[k] = v } return data } -// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. -func (m *IntAnyMap) MapStrAny() map[string]interface{} { +// MapStrAny returns a copy of the underlying data of the map as map[string]any. +func (m *IntAnyMap) MapStrAny() map[string]any { m.mu.RLock() - data := make(map[string]interface{}, len(m.data)) + data := make(map[string]any, len(m.data)) for k, v := range m.data { data[gconv.String(k)] = v } @@ -87,10 +87,10 @@ func (m *IntAnyMap) MapStrAny() map[string]interface{} { } // MapCopy returns a copy of the underlying data of the hash map. -func (m *IntAnyMap) MapCopy() map[int]interface{} { +func (m *IntAnyMap) MapCopy() map[int]any { m.mu.RLock() defer m.mu.RUnlock() - data := make(map[int]interface{}, len(m.data)) + data := make(map[int]any, len(m.data)) for k, v := range m.data { data[k] = v } @@ -121,17 +121,17 @@ func (m *IntAnyMap) FilterNil() { } // Set sets key-value to the hash map. -func (m *IntAnyMap) Set(key int, val interface{}) { +func (m *IntAnyMap) Set(key int, val any) { m.mu.Lock() if m.data == nil { - m.data = make(map[int]interface{}) + m.data = make(map[int]any) } m.data[key] = val m.mu.Unlock() } // Sets batch sets key-values to the hash map. -func (m *IntAnyMap) Sets(data map[int]interface{}) { +func (m *IntAnyMap) Sets(data map[int]any) { m.mu.Lock() if m.data == nil { m.data = data @@ -145,7 +145,7 @@ func (m *IntAnyMap) Sets(data map[int]interface{}) { // Search searches the map with given `key`. // Second return parameter `found` is true if key was found, otherwise false. -func (m *IntAnyMap) Search(key int) (value interface{}, found bool) { +func (m *IntAnyMap) Search(key int) (value any, found bool) { m.mu.RLock() if m.data != nil { value, found = m.data[key] @@ -155,7 +155,7 @@ func (m *IntAnyMap) Search(key int) (value interface{}, found bool) { } // Get returns the value by given `key`. -func (m *IntAnyMap) Get(key int) (value interface{}) { +func (m *IntAnyMap) Get(key int) (value any) { m.mu.RLock() if m.data != nil { value = m.data[key] @@ -165,7 +165,7 @@ func (m *IntAnyMap) Get(key int) (value interface{}) { } // Pop retrieves and deletes an item from the map. -func (m *IntAnyMap) Pop() (key int, value interface{}) { +func (m *IntAnyMap) Pop() (key int, value any) { m.mu.Lock() defer m.mu.Unlock() for key, value = range m.data { @@ -177,7 +177,7 @@ func (m *IntAnyMap) Pop() (key int, value interface{}) { // Pops retrieves and deletes `size` items from the map. // It returns all items if size == -1. -func (m *IntAnyMap) Pops(size int) map[int]interface{} { +func (m *IntAnyMap) Pops(size int) map[int]any { m.mu.Lock() defer m.mu.Unlock() if size > len(m.data) || size == -1 { @@ -188,7 +188,7 @@ func (m *IntAnyMap) Pops(size int) map[int]interface{} { } var ( index = 0 - newMap = make(map[int]interface{}, size) + newMap = make(map[int]any, size) ) for k, v := range m.data { delete(m.data, k) @@ -210,16 +210,16 @@ func (m *IntAnyMap) Pops(size int) map[int]interface{} { // and its return value will be set to the map with `key`. // // It returns value with given `key`. -func (m *IntAnyMap) doSetWithLockCheck(key int, value interface{}) interface{} { +func (m *IntAnyMap) doSetWithLockCheck(key int, value any) any { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[int]interface{}) + m.data = make(map[int]any) } if v, ok := m.data[key]; ok { return v } - if f, ok := value.(func() interface{}); ok { + if f, ok := value.(func() any); ok { value = f() } if value != nil { @@ -230,7 +230,7 @@ func (m *IntAnyMap) doSetWithLockCheck(key int, value interface{}) interface{} { // GetOrSet returns the value by key, // or sets value with given `value` if it does not exist and then returns this value. -func (m *IntAnyMap) GetOrSet(key int, value interface{}) interface{} { +func (m *IntAnyMap) GetOrSet(key int, value any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, value) } else { @@ -240,7 +240,7 @@ func (m *IntAnyMap) GetOrSet(key int, value interface{}) interface{} { // GetOrSetFunc returns the value by key, // or sets value with returned value of callback function `f` if it does not exist and returns this value. -func (m *IntAnyMap) GetOrSetFunc(key int, f func() interface{}) interface{} { +func (m *IntAnyMap) GetOrSetFunc(key int, f func() any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, f()) } else { @@ -253,7 +253,7 @@ func (m *IntAnyMap) GetOrSetFunc(key int, f func() interface{}) interface{} { // // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` // with mutex.Lock of the hash map. -func (m *IntAnyMap) GetOrSetFuncLock(key int, f func() interface{}) interface{} { +func (m *IntAnyMap) GetOrSetFuncLock(key int, f func() any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, f) } else { @@ -269,25 +269,25 @@ func (m *IntAnyMap) GetVar(key int) *gvar.Var { // GetVarOrSet returns a Var with result from GetVarOrSet. // The returned Var is un-concurrent safe. -func (m *IntAnyMap) GetVarOrSet(key int, value interface{}) *gvar.Var { +func (m *IntAnyMap) GetVarOrSet(key int, value any) *gvar.Var { return gvar.New(m.GetOrSet(key, value)) } // GetVarOrSetFunc returns a Var with result from GetOrSetFunc. // The returned Var is un-concurrent safe. -func (m *IntAnyMap) GetVarOrSetFunc(key int, f func() interface{}) *gvar.Var { +func (m *IntAnyMap) GetVarOrSetFunc(key int, f func() any) *gvar.Var { return gvar.New(m.GetOrSetFunc(key, f)) } // GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock. // The returned Var is un-concurrent safe. -func (m *IntAnyMap) GetVarOrSetFuncLock(key int, f func() interface{}) *gvar.Var { +func (m *IntAnyMap) GetVarOrSetFuncLock(key int, f func() any) *gvar.Var { return gvar.New(m.GetOrSetFuncLock(key, f)) } // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true. // It returns false if `key` exists, and `value` would be ignored. -func (m *IntAnyMap) SetIfNotExist(key int, value interface{}) bool { +func (m *IntAnyMap) SetIfNotExist(key int, value any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, value) return true @@ -297,7 +297,7 @@ func (m *IntAnyMap) SetIfNotExist(key int, value interface{}) bool { // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true. // It returns false if `key` exists, and `value` would be ignored. -func (m *IntAnyMap) SetIfNotExistFunc(key int, f func() interface{}) bool { +func (m *IntAnyMap) SetIfNotExistFunc(key int, f func() any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, f()) return true @@ -310,7 +310,7 @@ func (m *IntAnyMap) SetIfNotExistFunc(key int, f func() interface{}) bool { // // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that // it executes function `f` with mutex.Lock of the hash map. -func (m *IntAnyMap) SetIfNotExistFuncLock(key int, f func() interface{}) bool { +func (m *IntAnyMap) SetIfNotExistFuncLock(key int, f func() any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, f) return true @@ -330,7 +330,7 @@ func (m *IntAnyMap) Removes(keys []int) { } // Remove deletes value from map by given `key`, and return this deleted value. -func (m *IntAnyMap) Remove(key int) (value interface{}) { +func (m *IntAnyMap) Remove(key int) (value any) { m.mu.Lock() if m.data != nil { var ok bool @@ -358,10 +358,10 @@ func (m *IntAnyMap) Keys() []int { } // Values returns all values of the map as a slice. -func (m *IntAnyMap) Values() []interface{} { +func (m *IntAnyMap) Values() []any { m.mu.RLock() var ( - values = make([]interface{}, len(m.data)) + values = make([]any, len(m.data)) index = 0 ) for _, value := range m.data { @@ -401,26 +401,26 @@ func (m *IntAnyMap) IsEmpty() bool { // Clear deletes all data of the map, it will remake a new underlying data map. func (m *IntAnyMap) Clear() { m.mu.Lock() - m.data = make(map[int]interface{}) + m.data = make(map[int]any) m.mu.Unlock() } // Replace the data of the map with given `data`. -func (m *IntAnyMap) Replace(data map[int]interface{}) { +func (m *IntAnyMap) Replace(data map[int]any) { m.mu.Lock() m.data = data m.mu.Unlock() } // LockFunc locks writing with given callback function `f` within RWMutex.Lock. -func (m *IntAnyMap) LockFunc(f func(m map[int]interface{})) { +func (m *IntAnyMap) LockFunc(f func(m map[int]any)) { m.mu.Lock() defer m.mu.Unlock() f(m.data) } // RLockFunc locks reading with given callback function `f` within RWMutex.RLock. -func (m *IntAnyMap) RLockFunc(f func(m map[int]interface{})) { +func (m *IntAnyMap) RLockFunc(f func(m map[int]any)) { m.mu.RLock() defer m.mu.RUnlock() f(m.data) @@ -430,7 +430,7 @@ func (m *IntAnyMap) RLockFunc(f func(m map[int]interface{})) { func (m *IntAnyMap) Flip() { m.mu.Lock() defer m.mu.Unlock() - n := make(map[int]interface{}, len(m.data)) + n := make(map[int]any, len(m.data)) for k, v := range m.data { n[gconv.Int(v)] = k } @@ -476,7 +476,7 @@ func (m *IntAnyMap) UnmarshalJSON(b []byte) error { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[int]interface{}) + m.data = make(map[int]any) } if err := json.UnmarshalUseNumber(b, &m.data); err != nil { return err @@ -485,11 +485,11 @@ func (m *IntAnyMap) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for map. -func (m *IntAnyMap) UnmarshalValue(value interface{}) (err error) { +func (m *IntAnyMap) UnmarshalValue(value any) (err error) { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[int]interface{}) + m.data = make(map[int]any) } switch value.(type) { case string, []byte: @@ -503,13 +503,13 @@ func (m *IntAnyMap) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (m *IntAnyMap) DeepCopy() interface{} { +func (m *IntAnyMap) DeepCopy() any { if m == nil { return nil } m.mu.RLock() defer m.mu.RUnlock() - data := make(map[int]interface{}, len(m.data)) + data := make(map[int]any, len(m.data)) for k, v := range m.data { data[k] = deepcopy.Copy(v) } diff --git a/container/gmap/gmap_hash_int_int_map.go b/container/gmap/gmap_hash_int_int_map.go index 0a221e830b4..eb71c81fee7 100644 --- a/container/gmap/gmap_hash_int_int_map.go +++ b/container/gmap/gmap_hash_int_int_map.go @@ -70,10 +70,10 @@ func (m *IntIntMap) Map() map[int]int { return data } -// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. -func (m *IntIntMap) MapStrAny() map[string]interface{} { +// MapStrAny returns a copy of the underlying data of the map as map[string]any. +func (m *IntIntMap) MapStrAny() map[string]any { m.mu.RLock() - data := make(map[string]interface{}, len(m.data)) + data := make(map[string]any, len(m.data)) for k, v := range m.data { data[gconv.String(k)] = v } @@ -453,7 +453,7 @@ func (m *IntIntMap) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for map. -func (m *IntIntMap) UnmarshalValue(value interface{}) (err error) { +func (m *IntIntMap) UnmarshalValue(value any) (err error) { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { @@ -471,7 +471,7 @@ func (m *IntIntMap) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (m *IntIntMap) DeepCopy() interface{} { +func (m *IntIntMap) DeepCopy() any { if m == nil { return nil } diff --git a/container/gmap/gmap_hash_int_str_map.go b/container/gmap/gmap_hash_int_str_map.go index 4e976111fb3..dfdba27bca7 100644 --- a/container/gmap/gmap_hash_int_str_map.go +++ b/container/gmap/gmap_hash_int_str_map.go @@ -70,10 +70,10 @@ func (m *IntStrMap) Map() map[int]string { return data } -// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. -func (m *IntStrMap) MapStrAny() map[string]interface{} { +// MapStrAny returns a copy of the underlying data of the map as map[string]any. +func (m *IntStrMap) MapStrAny() map[string]any { m.mu.RLock() - data := make(map[string]interface{}, len(m.data)) + data := make(map[string]any, len(m.data)) for k, v := range m.data { data[gconv.String(k)] = v } @@ -453,7 +453,7 @@ func (m *IntStrMap) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for map. -func (m *IntStrMap) UnmarshalValue(value interface{}) (err error) { +func (m *IntStrMap) UnmarshalValue(value any) (err error) { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { @@ -471,7 +471,7 @@ func (m *IntStrMap) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (m *IntStrMap) DeepCopy() interface{} { +func (m *IntStrMap) DeepCopy() any { if m == nil { return nil } diff --git a/container/gmap/gmap_hash_str_any_map.go b/container/gmap/gmap_hash_str_any_map.go index 60f60c218f6..467b956c832 100644 --- a/container/gmap/gmap_hash_str_any_map.go +++ b/container/gmap/gmap_hash_str_any_map.go @@ -18,10 +18,10 @@ import ( "github.com/gogf/gf/v2/util/gconv" ) -// StrAnyMap implements map[string]interface{} with RWMutex that has switch. +// StrAnyMap implements map[string]any with RWMutex that has switch. type StrAnyMap struct { mu rwmutex.RWMutex - data map[string]interface{} + data map[string]any } // NewStrAnyMap returns an empty StrAnyMap object. @@ -30,14 +30,14 @@ type StrAnyMap struct { func NewStrAnyMap(safe ...bool) *StrAnyMap { return &StrAnyMap{ mu: rwmutex.Create(safe...), - data: make(map[string]interface{}), + data: make(map[string]any), } } // NewStrAnyMapFrom creates and returns a hash map from given map `data`. // Note that, the param `data` map will be set as the underlying data map(no deep copy), // there might be some concurrent-safe issues when changing the map outside. -func NewStrAnyMapFrom(data map[string]interface{}, safe ...bool) *StrAnyMap { +func NewStrAnyMapFrom(data map[string]any, safe ...bool) *StrAnyMap { return &StrAnyMap{ mu: rwmutex.Create(safe...), data: data, @@ -46,7 +46,7 @@ func NewStrAnyMapFrom(data map[string]interface{}, safe ...bool) *StrAnyMap { // Iterator iterates the hash map readonly with custom callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. -func (m *StrAnyMap) Iterator(f func(k string, v interface{}) bool) { +func (m *StrAnyMap) Iterator(f func(k string, v any) bool) { for k, v := range m.Map() { if !f(k, v) { break @@ -62,29 +62,29 @@ func (m *StrAnyMap) Clone() *StrAnyMap { // Map returns the underlying data map. // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, // or else a pointer to the underlying data. -func (m *StrAnyMap) Map() map[string]interface{} { +func (m *StrAnyMap) Map() map[string]any { m.mu.RLock() defer m.mu.RUnlock() if !m.mu.IsSafe() { return m.data } - data := make(map[string]interface{}, len(m.data)) + data := make(map[string]any, len(m.data)) for k, v := range m.data { data[k] = v } return data } -// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. -func (m *StrAnyMap) MapStrAny() map[string]interface{} { +// MapStrAny returns a copy of the underlying data of the map as map[string]any. +func (m *StrAnyMap) MapStrAny() map[string]any { return m.Map() } // MapCopy returns a copy of the underlying data of the hash map. -func (m *StrAnyMap) MapCopy() map[string]interface{} { +func (m *StrAnyMap) MapCopy() map[string]any { m.mu.RLock() defer m.mu.RUnlock() - data := make(map[string]interface{}, len(m.data)) + data := make(map[string]any, len(m.data)) for k, v := range m.data { data[k] = v } @@ -115,17 +115,17 @@ func (m *StrAnyMap) FilterNil() { } // Set sets key-value to the hash map. -func (m *StrAnyMap) Set(key string, val interface{}) { +func (m *StrAnyMap) Set(key string, val any) { m.mu.Lock() if m.data == nil { - m.data = make(map[string]interface{}) + m.data = make(map[string]any) } m.data[key] = val m.mu.Unlock() } // Sets batch sets key-values to the hash map. -func (m *StrAnyMap) Sets(data map[string]interface{}) { +func (m *StrAnyMap) Sets(data map[string]any) { m.mu.Lock() if m.data == nil { m.data = data @@ -139,7 +139,7 @@ func (m *StrAnyMap) Sets(data map[string]interface{}) { // Search searches the map with given `key`. // Second return parameter `found` is true if key was found, otherwise false. -func (m *StrAnyMap) Search(key string) (value interface{}, found bool) { +func (m *StrAnyMap) Search(key string) (value any, found bool) { m.mu.RLock() if m.data != nil { value, found = m.data[key] @@ -149,7 +149,7 @@ func (m *StrAnyMap) Search(key string) (value interface{}, found bool) { } // Get returns the value by given `key`. -func (m *StrAnyMap) Get(key string) (value interface{}) { +func (m *StrAnyMap) Get(key string) (value any) { m.mu.RLock() if m.data != nil { value = m.data[key] @@ -159,7 +159,7 @@ func (m *StrAnyMap) Get(key string) (value interface{}) { } // Pop retrieves and deletes an item from the map. -func (m *StrAnyMap) Pop() (key string, value interface{}) { +func (m *StrAnyMap) Pop() (key string, value any) { m.mu.Lock() defer m.mu.Unlock() for key, value = range m.data { @@ -171,7 +171,7 @@ func (m *StrAnyMap) Pop() (key string, value interface{}) { // Pops retrieves and deletes `size` items from the map. // It returns all items if size == -1. -func (m *StrAnyMap) Pops(size int) map[string]interface{} { +func (m *StrAnyMap) Pops(size int) map[string]any { m.mu.Lock() defer m.mu.Unlock() if size > len(m.data) || size == -1 { @@ -182,7 +182,7 @@ func (m *StrAnyMap) Pops(size int) map[string]interface{} { } var ( index = 0 - newMap = make(map[string]interface{}, size) + newMap = make(map[string]any, size) ) for k, v := range m.data { delete(m.data, k) @@ -204,16 +204,16 @@ func (m *StrAnyMap) Pops(size int) map[string]interface{} { // and its return value will be set to the map with `key`. // // It returns value with given `key`. -func (m *StrAnyMap) doSetWithLockCheck(key string, value interface{}) interface{} { +func (m *StrAnyMap) doSetWithLockCheck(key string, value any) any { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[string]interface{}) + m.data = make(map[string]any) } if v, ok := m.data[key]; ok { return v } - if f, ok := value.(func() interface{}); ok { + if f, ok := value.(func() any); ok { value = f() } if value != nil { @@ -224,7 +224,7 @@ func (m *StrAnyMap) doSetWithLockCheck(key string, value interface{}) interface{ // GetOrSet returns the value by key, // or sets value with given `value` if it does not exist and then returns this value. -func (m *StrAnyMap) GetOrSet(key string, value interface{}) interface{} { +func (m *StrAnyMap) GetOrSet(key string, value any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, value) } else { @@ -235,7 +235,7 @@ func (m *StrAnyMap) GetOrSet(key string, value interface{}) interface{} { // GetOrSetFunc returns the value by key, // or sets value with returned value of callback function `f` if it does not exist // and then returns this value. -func (m *StrAnyMap) GetOrSetFunc(key string, f func() interface{}) interface{} { +func (m *StrAnyMap) GetOrSetFunc(key string, f func() any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, f()) } else { @@ -249,7 +249,7 @@ func (m *StrAnyMap) GetOrSetFunc(key string, f func() interface{}) interface{} { // // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` // with mutex.Lock of the hash map. -func (m *StrAnyMap) GetOrSetFuncLock(key string, f func() interface{}) interface{} { +func (m *StrAnyMap) GetOrSetFuncLock(key string, f func() any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, f) } else { @@ -265,25 +265,25 @@ func (m *StrAnyMap) GetVar(key string) *gvar.Var { // GetVarOrSet returns a Var with result from GetVarOrSet. // The returned Var is un-concurrent safe. -func (m *StrAnyMap) GetVarOrSet(key string, value interface{}) *gvar.Var { +func (m *StrAnyMap) GetVarOrSet(key string, value any) *gvar.Var { return gvar.New(m.GetOrSet(key, value)) } // GetVarOrSetFunc returns a Var with result from GetOrSetFunc. // The returned Var is un-concurrent safe. -func (m *StrAnyMap) GetVarOrSetFunc(key string, f func() interface{}) *gvar.Var { +func (m *StrAnyMap) GetVarOrSetFunc(key string, f func() any) *gvar.Var { return gvar.New(m.GetOrSetFunc(key, f)) } // GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock. // The returned Var is un-concurrent safe. -func (m *StrAnyMap) GetVarOrSetFuncLock(key string, f func() interface{}) *gvar.Var { +func (m *StrAnyMap) GetVarOrSetFuncLock(key string, f func() any) *gvar.Var { return gvar.New(m.GetOrSetFuncLock(key, f)) } // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true. // It returns false if `key` exists, and `value` would be ignored. -func (m *StrAnyMap) SetIfNotExist(key string, value interface{}) bool { +func (m *StrAnyMap) SetIfNotExist(key string, value any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, value) return true @@ -293,7 +293,7 @@ func (m *StrAnyMap) SetIfNotExist(key string, value interface{}) bool { // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true. // It returns false if `key` exists, and `value` would be ignored. -func (m *StrAnyMap) SetIfNotExistFunc(key string, f func() interface{}) bool { +func (m *StrAnyMap) SetIfNotExistFunc(key string, f func() any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, f()) return true @@ -306,7 +306,7 @@ func (m *StrAnyMap) SetIfNotExistFunc(key string, f func() interface{}) bool { // // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that // it executes function `f` with mutex.Lock of the hash map. -func (m *StrAnyMap) SetIfNotExistFuncLock(key string, f func() interface{}) bool { +func (m *StrAnyMap) SetIfNotExistFuncLock(key string, f func() any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, f) return true @@ -326,7 +326,7 @@ func (m *StrAnyMap) Removes(keys []string) { } // Remove deletes value from map by given `key`, and return this deleted value. -func (m *StrAnyMap) Remove(key string) (value interface{}) { +func (m *StrAnyMap) Remove(key string) (value any) { m.mu.Lock() if m.data != nil { var ok bool @@ -354,10 +354,10 @@ func (m *StrAnyMap) Keys() []string { } // Values returns all values of the map as a slice. -func (m *StrAnyMap) Values() []interface{} { +func (m *StrAnyMap) Values() []any { m.mu.RLock() var ( - values = make([]interface{}, len(m.data)) + values = make([]any, len(m.data)) index = 0 ) for _, value := range m.data { @@ -397,26 +397,26 @@ func (m *StrAnyMap) IsEmpty() bool { // Clear deletes all data of the map, it will remake a new underlying data map. func (m *StrAnyMap) Clear() { m.mu.Lock() - m.data = make(map[string]interface{}) + m.data = make(map[string]any) m.mu.Unlock() } // Replace the data of the map with given `data`. -func (m *StrAnyMap) Replace(data map[string]interface{}) { +func (m *StrAnyMap) Replace(data map[string]any) { m.mu.Lock() m.data = data m.mu.Unlock() } // LockFunc locks writing with given callback function `f` within RWMutex.Lock. -func (m *StrAnyMap) LockFunc(f func(m map[string]interface{})) { +func (m *StrAnyMap) LockFunc(f func(m map[string]any)) { m.mu.Lock() defer m.mu.Unlock() f(m.data) } // RLockFunc locks reading with given callback function `f` within RWMutex.RLock. -func (m *StrAnyMap) RLockFunc(f func(m map[string]interface{})) { +func (m *StrAnyMap) RLockFunc(f func(m map[string]any)) { m.mu.RLock() defer m.mu.RUnlock() f(m.data) @@ -426,7 +426,7 @@ func (m *StrAnyMap) RLockFunc(f func(m map[string]interface{})) { func (m *StrAnyMap) Flip() { m.mu.Lock() defer m.mu.Unlock() - n := make(map[string]interface{}, len(m.data)) + n := make(map[string]any, len(m.data)) for k, v := range m.data { n[gconv.String(v)] = k } @@ -472,7 +472,7 @@ func (m *StrAnyMap) UnmarshalJSON(b []byte) error { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[string]interface{}) + m.data = make(map[string]any) } if err := json.UnmarshalUseNumber(b, &m.data); err != nil { return err @@ -481,7 +481,7 @@ func (m *StrAnyMap) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for map. -func (m *StrAnyMap) UnmarshalValue(value interface{}) (err error) { +func (m *StrAnyMap) UnmarshalValue(value any) (err error) { m.mu.Lock() defer m.mu.Unlock() m.data = gconv.Map(value) @@ -489,13 +489,13 @@ func (m *StrAnyMap) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (m *StrAnyMap) DeepCopy() interface{} { +func (m *StrAnyMap) DeepCopy() any { if m == nil { return nil } m.mu.RLock() defer m.mu.RUnlock() - data := make(map[string]interface{}, len(m.data)) + data := make(map[string]any, len(m.data)) for k, v := range m.data { data[k] = deepcopy.Copy(v) } diff --git a/container/gmap/gmap_hash_str_int_map.go b/container/gmap/gmap_hash_str_int_map.go index c44d3e11e6f..f9c582d5583 100644 --- a/container/gmap/gmap_hash_str_int_map.go +++ b/container/gmap/gmap_hash_str_int_map.go @@ -71,11 +71,11 @@ func (m *StrIntMap) Map() map[string]int { return data } -// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. -func (m *StrIntMap) MapStrAny() map[string]interface{} { +// MapStrAny returns a copy of the underlying data of the map as map[string]any. +func (m *StrIntMap) MapStrAny() map[string]any { m.mu.RLock() defer m.mu.RUnlock() - data := make(map[string]interface{}, len(m.data)) + data := make(map[string]any, len(m.data)) for k, v := range m.data { data[k] = v } @@ -457,7 +457,7 @@ func (m *StrIntMap) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for map. -func (m *StrIntMap) UnmarshalValue(value interface{}) (err error) { +func (m *StrIntMap) UnmarshalValue(value any) (err error) { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { @@ -475,7 +475,7 @@ func (m *StrIntMap) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (m *StrIntMap) DeepCopy() interface{} { +func (m *StrIntMap) DeepCopy() any { if m == nil { return nil } diff --git a/container/gmap/gmap_hash_str_str_map.go b/container/gmap/gmap_hash_str_str_map.go index 5665bdefb74..b346bdfb23c 100644 --- a/container/gmap/gmap_hash_str_str_map.go +++ b/container/gmap/gmap_hash_str_str_map.go @@ -71,10 +71,10 @@ func (m *StrStrMap) Map() map[string]string { return data } -// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. -func (m *StrStrMap) MapStrAny() map[string]interface{} { +// MapStrAny returns a copy of the underlying data of the map as map[string]any. +func (m *StrStrMap) MapStrAny() map[string]any { m.mu.RLock() - data := make(map[string]interface{}, len(m.data)) + data := make(map[string]any, len(m.data)) for k, v := range m.data { data[k] = v } @@ -456,7 +456,7 @@ func (m *StrStrMap) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for map. -func (m *StrStrMap) UnmarshalValue(value interface{}) (err error) { +func (m *StrStrMap) UnmarshalValue(value any) (err error) { m.mu.Lock() defer m.mu.Unlock() m.data = gconv.MapStrStr(value) @@ -464,7 +464,7 @@ func (m *StrStrMap) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (m *StrStrMap) DeepCopy() interface{} { +func (m *StrStrMap) DeepCopy() any { if m == nil { return nil } diff --git a/container/gmap/gmap_list_map.go b/container/gmap/gmap_list_map.go index af2d66ec120..cfb3791d835 100644 --- a/container/gmap/gmap_list_map.go +++ b/container/gmap/gmap_list_map.go @@ -28,13 +28,13 @@ import ( // Reference: http://en.wikipedia.org/wiki/Associative_array type ListMap struct { mu rwmutex.RWMutex - data map[interface{}]*glist.Element + data map[any]*glist.Element list *glist.List } type gListMapNode struct { - key interface{} - value interface{} + key any + value any } // NewListMap returns an empty link map. @@ -44,7 +44,7 @@ type gListMapNode struct { func NewListMap(safe ...bool) *ListMap { return &ListMap{ mu: rwmutex.Create(safe...), - data: make(map[interface{}]*glist.Element), + data: make(map[any]*glist.Element), list: glist.New(), } } @@ -52,20 +52,20 @@ func NewListMap(safe ...bool) *ListMap { // NewListMapFrom returns a link map from given map `data`. // Note that, the param `data` map will be set as the underlying data map(no deep copy), // there might be some concurrent-safe issues when changing the map outside. -func NewListMapFrom(data map[interface{}]interface{}, safe ...bool) *ListMap { +func NewListMapFrom(data map[any]any, safe ...bool) *ListMap { m := NewListMap(safe...) m.Sets(data) return m } // Iterator is alias of IteratorAsc. -func (m *ListMap) Iterator(f func(key, value interface{}) bool) { +func (m *ListMap) Iterator(f func(key, value any) bool) { m.IteratorAsc(f) } // IteratorAsc iterates the map readonly in ascending order with given callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. -func (m *ListMap) IteratorAsc(f func(key interface{}, value interface{}) bool) { +func (m *ListMap) IteratorAsc(f func(key any, value any) bool) { m.mu.RLock() defer m.mu.RUnlock() if m.list != nil { @@ -79,7 +79,7 @@ func (m *ListMap) IteratorAsc(f func(key interface{}, value interface{}) bool) { // IteratorDesc iterates the map readonly in descending order with given callback function `f`. // If `f` returns true, then it continues iterating; or false to stop. -func (m *ListMap) IteratorDesc(f func(key interface{}, value interface{}) bool) { +func (m *ListMap) IteratorDesc(f func(key any, value any) bool) { m.mu.RLock() defer m.mu.RUnlock() if m.list != nil { @@ -99,15 +99,15 @@ func (m *ListMap) Clone(safe ...bool) *ListMap { // Clear deletes all data of the map, it will remake a new underlying data map. func (m *ListMap) Clear() { m.mu.Lock() - m.data = make(map[interface{}]*glist.Element) + m.data = make(map[any]*glist.Element) m.list = glist.New() m.mu.Unlock() } // Replace the data of the map with given `data`. -func (m *ListMap) Replace(data map[interface{}]interface{}) { +func (m *ListMap) Replace(data map[any]any) { m.mu.Lock() - m.data = make(map[interface{}]*glist.Element) + m.data = make(map[any]*glist.Element) m.list = glist.New() for key, value := range data { if e, ok := m.data[key]; !ok { @@ -120,12 +120,12 @@ func (m *ListMap) Replace(data map[interface{}]interface{}) { } // Map returns a copy of the underlying data of the map. -func (m *ListMap) Map() map[interface{}]interface{} { +func (m *ListMap) Map() map[any]any { m.mu.RLock() var node *gListMapNode - var data map[interface{}]interface{} + var data map[any]any if m.list != nil { - data = make(map[interface{}]interface{}, len(m.data)) + data = make(map[any]any, len(m.data)) m.list.IteratorAsc(func(e *glist.Element) bool { node = e.Value.(*gListMapNode) data[node.key] = node.value @@ -136,13 +136,13 @@ func (m *ListMap) Map() map[interface{}]interface{} { return data } -// MapStrAny returns a copy of the underlying data of the map as map[string]interface{}. -func (m *ListMap) MapStrAny() map[string]interface{} { +// MapStrAny returns a copy of the underlying data of the map as map[string]any. +func (m *ListMap) MapStrAny() map[string]any { m.mu.RLock() var node *gListMapNode - var data map[string]interface{} + var data map[string]any if m.list != nil { - data = make(map[string]interface{}, len(m.data)) + data = make(map[string]any, len(m.data)) m.list.IteratorAsc(func(e *glist.Element) bool { node = e.Value.(*gListMapNode) data[gconv.String(node.key)] = node.value @@ -158,7 +158,7 @@ func (m *ListMap) FilterEmpty() { m.mu.Lock() if m.list != nil { var ( - keys = make([]interface{}, 0) + keys = make([]any, 0) node *gListMapNode ) m.list.IteratorAsc(func(e *glist.Element) bool { @@ -181,10 +181,10 @@ func (m *ListMap) FilterEmpty() { } // Set sets key-value to the map. -func (m *ListMap) Set(key interface{}, value interface{}) { +func (m *ListMap) Set(key any, value any) { m.mu.Lock() if m.data == nil { - m.data = make(map[interface{}]*glist.Element) + m.data = make(map[any]*glist.Element) m.list = glist.New() } if e, ok := m.data[key]; !ok { @@ -196,10 +196,10 @@ func (m *ListMap) Set(key interface{}, value interface{}) { } // Sets batch sets key-values to the map. -func (m *ListMap) Sets(data map[interface{}]interface{}) { +func (m *ListMap) Sets(data map[any]any) { m.mu.Lock() if m.data == nil { - m.data = make(map[interface{}]*glist.Element) + m.data = make(map[any]*glist.Element) m.list = glist.New() } for key, value := range data { @@ -214,7 +214,7 @@ func (m *ListMap) Sets(data map[interface{}]interface{}) { // Search searches the map with given `key`. // Second return parameter `found` is true if key was found, otherwise false. -func (m *ListMap) Search(key interface{}) (value interface{}, found bool) { +func (m *ListMap) Search(key any) (value any, found bool) { m.mu.RLock() if m.data != nil { if e, ok := m.data[key]; ok { @@ -227,7 +227,7 @@ func (m *ListMap) Search(key interface{}) (value interface{}, found bool) { } // Get returns the value by given `key`. -func (m *ListMap) Get(key interface{}) (value interface{}) { +func (m *ListMap) Get(key any) (value any) { m.mu.RLock() if m.data != nil { if e, ok := m.data[key]; ok { @@ -239,7 +239,7 @@ func (m *ListMap) Get(key interface{}) (value interface{}) { } // Pop retrieves and deletes an item from the map. -func (m *ListMap) Pop() (key, value interface{}) { +func (m *ListMap) Pop() (key, value any) { m.mu.Lock() defer m.mu.Unlock() for k, e := range m.data { @@ -253,7 +253,7 @@ func (m *ListMap) Pop() (key, value interface{}) { // Pops retrieves and deletes `size` items from the map. // It returns all items if size == -1. -func (m *ListMap) Pops(size int) map[interface{}]interface{} { +func (m *ListMap) Pops(size int) map[any]any { m.mu.Lock() defer m.mu.Unlock() if size > len(m.data) || size == -1 { @@ -263,7 +263,7 @@ func (m *ListMap) Pops(size int) map[interface{}]interface{} { return nil } index := 0 - newMap := make(map[interface{}]interface{}, size) + newMap := make(map[any]any, size) for k, e := range m.data { value := e.Value.(*gListMapNode).value delete(m.data, k) @@ -286,17 +286,17 @@ func (m *ListMap) Pops(size int) map[interface{}]interface{} { // and its return value will be set to the map with `key`. // // It returns value with given `key`. -func (m *ListMap) doSetWithLockCheck(key interface{}, value interface{}) interface{} { +func (m *ListMap) doSetWithLockCheck(key any, value any) any { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[interface{}]*glist.Element) + m.data = make(map[any]*glist.Element) m.list = glist.New() } if e, ok := m.data[key]; ok { return e.Value.(*gListMapNode).value } - if f, ok := value.(func() interface{}); ok { + if f, ok := value.(func() any); ok { value = f() } if value != nil { @@ -307,7 +307,7 @@ func (m *ListMap) doSetWithLockCheck(key interface{}, value interface{}) interfa // GetOrSet returns the value by key, // or sets value with given `value` if it does not exist and then returns this value. -func (m *ListMap) GetOrSet(key interface{}, value interface{}) interface{} { +func (m *ListMap) GetOrSet(key any, value any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, value) } else { @@ -318,7 +318,7 @@ func (m *ListMap) GetOrSet(key interface{}, value interface{}) interface{} { // GetOrSetFunc returns the value by key, // or sets value with returned value of callback function `f` if it does not exist // and then returns this value. -func (m *ListMap) GetOrSetFunc(key interface{}, f func() interface{}) interface{} { +func (m *ListMap) GetOrSetFunc(key any, f func() any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, f()) } else { @@ -332,7 +332,7 @@ func (m *ListMap) GetOrSetFunc(key interface{}, f func() interface{}) interface{ // // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` // with mutex.Lock of the map. -func (m *ListMap) GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} { +func (m *ListMap) GetOrSetFuncLock(key any, f func() any) any { if v, ok := m.Search(key); !ok { return m.doSetWithLockCheck(key, f) } else { @@ -342,31 +342,31 @@ func (m *ListMap) GetOrSetFuncLock(key interface{}, f func() interface{}) interf // GetVar returns a Var with the value by given `key`. // The returned Var is un-concurrent safe. -func (m *ListMap) GetVar(key interface{}) *gvar.Var { +func (m *ListMap) GetVar(key any) *gvar.Var { return gvar.New(m.Get(key)) } // GetVarOrSet returns a Var with result from GetVarOrSet. // The returned Var is un-concurrent safe. -func (m *ListMap) GetVarOrSet(key interface{}, value interface{}) *gvar.Var { +func (m *ListMap) GetVarOrSet(key any, value any) *gvar.Var { return gvar.New(m.GetOrSet(key, value)) } // GetVarOrSetFunc returns a Var with result from GetOrSetFunc. // The returned Var is un-concurrent safe. -func (m *ListMap) GetVarOrSetFunc(key interface{}, f func() interface{}) *gvar.Var { +func (m *ListMap) GetVarOrSetFunc(key any, f func() any) *gvar.Var { return gvar.New(m.GetOrSetFunc(key, f)) } // GetVarOrSetFuncLock returns a Var with result from GetOrSetFuncLock. // The returned Var is un-concurrent safe. -func (m *ListMap) GetVarOrSetFuncLock(key interface{}, f func() interface{}) *gvar.Var { +func (m *ListMap) GetVarOrSetFuncLock(key any, f func() any) *gvar.Var { return gvar.New(m.GetOrSetFuncLock(key, f)) } // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true. // It returns false if `key` exists, and `value` would be ignored. -func (m *ListMap) SetIfNotExist(key interface{}, value interface{}) bool { +func (m *ListMap) SetIfNotExist(key any, value any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, value) return true @@ -376,7 +376,7 @@ func (m *ListMap) SetIfNotExist(key interface{}, value interface{}) bool { // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true. // It returns false if `key` exists, and `value` would be ignored. -func (m *ListMap) SetIfNotExistFunc(key interface{}, f func() interface{}) bool { +func (m *ListMap) SetIfNotExistFunc(key any, f func() any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, f()) return true @@ -389,7 +389,7 @@ func (m *ListMap) SetIfNotExistFunc(key interface{}, f func() interface{}) bool // // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that // it executes function `f` with mutex.Lock of the map. -func (m *ListMap) SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool { +func (m *ListMap) SetIfNotExistFuncLock(key any, f func() any) bool { if !m.Contains(key) { m.doSetWithLockCheck(key, f) return true @@ -398,7 +398,7 @@ func (m *ListMap) SetIfNotExistFuncLock(key interface{}, f func() interface{}) b } // Remove deletes value from map by given `key`, and return this deleted value. -func (m *ListMap) Remove(key interface{}) (value interface{}) { +func (m *ListMap) Remove(key any) (value any) { m.mu.Lock() if m.data != nil { if e, ok := m.data[key]; ok { @@ -412,7 +412,7 @@ func (m *ListMap) Remove(key interface{}) (value interface{}) { } // Removes batch deletes values of the map by keys. -func (m *ListMap) Removes(keys []interface{}) { +func (m *ListMap) Removes(keys []any) { m.mu.Lock() if m.data != nil { for _, key := range keys { @@ -426,10 +426,10 @@ func (m *ListMap) Removes(keys []interface{}) { } // Keys returns all keys of the map as a slice in ascending order. -func (m *ListMap) Keys() []interface{} { +func (m *ListMap) Keys() []any { m.mu.RLock() var ( - keys = make([]interface{}, m.list.Len()) + keys = make([]any, m.list.Len()) index = 0 ) if m.list != nil { @@ -444,10 +444,10 @@ func (m *ListMap) Keys() []interface{} { } // Values returns all values of the map as a slice. -func (m *ListMap) Values() []interface{} { +func (m *ListMap) Values() []any { m.mu.RLock() var ( - values = make([]interface{}, m.list.Len()) + values = make([]any, m.list.Len()) index = 0 ) if m.list != nil { @@ -463,7 +463,7 @@ func (m *ListMap) Values() []interface{} { // Contains checks whether a key exists. // It returns true if the `key` exists, or else false. -func (m *ListMap) Contains(key interface{}) (ok bool) { +func (m *ListMap) Contains(key any) (ok bool) { m.mu.RLock() if m.data != nil { _, ok = m.data[key] @@ -501,7 +501,7 @@ func (m *ListMap) Merge(other *ListMap) { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[interface{}]*glist.Element) + m.data = make(map[any]*glist.Element) m.list = glist.New() } if other != m { @@ -536,7 +536,7 @@ func (m ListMap) MarshalJSON() (jsonBytes []byte, err error) { } buffer := bytes.NewBuffer(nil) buffer.WriteByte('{') - m.Iterator(func(key, value interface{}) bool { + m.Iterator(func(key, value any) bool { valueBytes, valueJSONErr := json.Marshal(value) if valueJSONErr != nil { err = valueJSONErr @@ -557,10 +557,10 @@ func (m *ListMap) UnmarshalJSON(b []byte) error { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[interface{}]*glist.Element) + m.data = make(map[any]*glist.Element) m.list = glist.New() } - var data map[string]interface{} + var data map[string]any if err := json.UnmarshalUseNumber(b, &data); err != nil { return err } @@ -575,11 +575,11 @@ func (m *ListMap) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for map. -func (m *ListMap) UnmarshalValue(value interface{}) (err error) { +func (m *ListMap) UnmarshalValue(value any) (err error) { m.mu.Lock() defer m.mu.Unlock() if m.data == nil { - m.data = make(map[interface{}]*glist.Element) + m.data = make(map[any]*glist.Element) m.list = glist.New() } for k, v := range gconv.Map(value) { @@ -593,13 +593,13 @@ func (m *ListMap) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (m *ListMap) DeepCopy() interface{} { +func (m *ListMap) DeepCopy() any { if m == nil { return nil } m.mu.RLock() defer m.mu.RUnlock() - data := make(map[interface{}]interface{}, len(m.data)) + data := make(map[any]any, len(m.data)) if m.list != nil { var node *gListMapNode m.list.IteratorAsc(func(e *glist.Element) bool { diff --git a/container/gmap/gmap_tree_map.go b/container/gmap/gmap_tree_map.go index c81caa48a58..3e07d97ee25 100644 --- a/container/gmap/gmap_tree_map.go +++ b/container/gmap/gmap_tree_map.go @@ -16,7 +16,7 @@ type TreeMap = gtree.RedBlackTree // NewTreeMap instantiates a tree map with the custom comparator. // The parameter `safe` is used to specify whether using tree in concurrent-safety, // which is false in default. -func NewTreeMap(comparator func(v1, v2 interface{}) int, safe ...bool) *TreeMap { +func NewTreeMap(comparator func(v1, v2 any) int, safe ...bool) *TreeMap { return gtree.NewRedBlackTree(comparator, safe...) } @@ -25,6 +25,6 @@ func NewTreeMap(comparator func(v1, v2 interface{}) int, safe ...bool) *TreeMap // there might be some concurrent-safe issues when changing the map outside. // The parameter `safe` is used to specify whether using tree in concurrent-safety, // which is false in default. -func NewTreeMapFrom(comparator func(v1, v2 interface{}) int, data map[interface{}]interface{}, safe ...bool) *TreeMap { +func NewTreeMapFrom(comparator func(v1, v2 any) int, data map[any]any, safe ...bool) *TreeMap { return gtree.NewRedBlackTreeFrom(comparator, data, safe...) } diff --git a/container/gmap/gmap_z_basic_test.go b/container/gmap/gmap_z_basic_test.go index 2bc7013a91b..b2675228ab6 100644 --- a/container/gmap/gmap_z_basic_test.go +++ b/container/gmap/gmap_z_basic_test.go @@ -14,7 +14,7 @@ import ( "github.com/gogf/gf/v2/util/gutil" ) -func getValue() interface{} { +func getValue() any { return 3 } @@ -71,7 +71,7 @@ func Test_Map_Basic(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gmap.New() m.Set("key1", "val1") - t.Assert(m.Keys(), []interface{}{"key1"}) + t.Assert(m.Keys(), []any{"key1"}) t.Assert(m.Get("key1"), "val1") t.Assert(m.Size(), 1) @@ -91,14 +91,14 @@ func Test_Map_Basic(t *testing.T) { t.AssertIN("val1", m.Values()) m.Flip() - t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) + t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"}) m.Clear() t.Assert(m.Size(), 0) t.Assert(m.IsEmpty(), true) - m2 := gmap.NewFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) - t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, "key1": "val1"}) + m2 := gmap.NewFrom(map[any]any{1: 1, "key1": "val1"}) + t.Assert(m2.Map(), map[any]any{1: 1, "key1": "val1"}) }) } @@ -118,30 +118,30 @@ func Test_Map_Set_Fun(t *testing.T) { func Test_Map_Batch(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gmap.New() - m.Sets(map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - t.Assert(m.Map(), map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - m.Removes([]interface{}{"key1", 1}) - t.Assert(m.Map(), map[interface{}]interface{}{"key2": "val2", "key3": "val3"}) + m.Sets(map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + t.Assert(m.Map(), map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + m.Removes([]any{"key1", 1}) + t.Assert(m.Map(), map[any]any{"key2": "val2", "key3": "val3"}) }) } func Test_Map_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[interface{}]interface{}{1: 1, "key1": "val1"} + expect := map[any]any{1: 1, "key1": "val1"} m := gmap.NewFrom(expect) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { t.Assert(expect[k], v) return true }) // 断言返回值对遍历控制 i := 0 j := 0 - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { i++ return true }) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { j++ return false }) @@ -152,12 +152,12 @@ func Test_Map_Iterator(t *testing.T) { func Test_Map_Lock(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[interface{}]interface{}{1: 1, "key1": "val1"} + expect := map[any]any{1: 1, "key1": "val1"} m := gmap.NewFrom(expect) - m.LockFunc(func(m map[interface{}]interface{}) { + m.LockFunc(func(m map[any]any) { t.Assert(m, expect) }) - m.RLockFunc(func(m map[interface{}]interface{}) { + m.RLockFunc(func(m map[any]any) { t.Assert(m, expect) }) }) @@ -166,7 +166,7 @@ func Test_Map_Lock(t *testing.T) { func Test_Map_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { // clone 方法是深克隆 - m := gmap.NewFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) + m := gmap.NewFrom(map[any]any{1: 1, "key1": "val1"}) m_clone := m.Clone() m.Remove(1) // 修改原 map,clone 后的 map 不影响 @@ -185,6 +185,6 @@ func Test_Map_Basic_Merge(t *testing.T) { m1.Set("key1", "val1") m2.Set("key2", "val2") m1.Merge(m2) - t.Assert(m1.Map(), map[interface{}]interface{}{"key1": "val1", "key2": "val2"}) + t.Assert(m1.Map(), map[any]any{"key1": "val1", "key2": "val2"}) }) } diff --git a/container/gmap/gmap_z_example_any_any_test.go b/container/gmap/gmap_z_example_any_any_test.go index 67c03264991..bb53bd77633 100644 --- a/container/gmap/gmap_z_example_any_any_test.go +++ b/container/gmap/gmap_z_example_any_any_test.go @@ -22,7 +22,7 @@ func ExampleAnyAnyMap_Iterator() { } var totalKey, totalValue int - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { totalKey += k.(int) totalValue += v.(int) @@ -149,7 +149,7 @@ func ExampleAnyAnyMap_Set() { func ExampleAnyAnyMap_Sets() { m := gmap.New() - addMap := make(map[interface{}]interface{}) + addMap := make(map[any]any) addMap["key1"] = "val1" addMap["key2"] = "val2" addMap["key3"] = "val3" @@ -252,10 +252,10 @@ func ExampleAnyAnyMap_GetOrSetFunc() { m := gmap.New() m.Set("key1", "val1") - fmt.Println(m.GetOrSetFunc("key1", func() interface{} { + fmt.Println(m.GetOrSetFunc("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetOrSetFunc("key2", func() interface{} { + fmt.Println(m.GetOrSetFunc("key2", func() any { return "NotExistValue" })) @@ -268,10 +268,10 @@ func ExampleAnyAnyMap_GetOrSetFuncLock() { m := gmap.New() m.Set("key1", "val1") - fmt.Println(m.GetOrSetFuncLock("key1", func() interface{} { + fmt.Println(m.GetOrSetFuncLock("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetOrSetFuncLock("key2", func() interface{} { + fmt.Println(m.GetOrSetFuncLock("key2", func() any { return "NotExistValue" })) @@ -308,10 +308,10 @@ func ExampleAnyAnyMap_GetVarOrSetFunc() { m := gmap.New() m.Set("key1", "val1") - fmt.Println(m.GetVarOrSetFunc("key1", func() interface{} { + fmt.Println(m.GetVarOrSetFunc("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetVarOrSetFunc("key2", func() interface{} { + fmt.Println(m.GetVarOrSetFunc("key2", func() any { return "NotExistValue" })) @@ -324,10 +324,10 @@ func ExampleAnyAnyMap_GetVarOrSetFuncLock() { m := gmap.New() m.Set("key1", "val1") - fmt.Println(m.GetVarOrSetFuncLock("key1", func() interface{} { + fmt.Println(m.GetVarOrSetFuncLock("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetVarOrSetFuncLock("key2", func() interface{} { + fmt.Println(m.GetVarOrSetFuncLock("key2", func() any { return "NotExistValue" })) @@ -350,10 +350,10 @@ func ExampleAnyAnyMap_SetIfNotExist() { func ExampleAnyAnyMap_SetIfNotExistFunc() { var m gmap.Map - fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFunc("k1", func() any { return "v1" })) - fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFunc("k1", func() any { return "v2" })) fmt.Println(m.Map()) @@ -366,10 +366,10 @@ func ExampleAnyAnyMap_SetIfNotExistFunc() { func ExampleAnyAnyMap_SetIfNotExistFuncLock() { var m gmap.Map - fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFuncLock("k1", func() any { return "v1" })) - fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFuncLock("k1", func() any { return "v2" })) fmt.Println(m.Map()) @@ -403,7 +403,7 @@ func ExampleAnyAnyMap_Removes() { "k4": "v4", }) - removeList := make([]interface{}, 2) + removeList := make([]any, 2) removeList = append(removeList, "k1") removeList = append(removeList, "k2") @@ -538,7 +538,7 @@ func ExampleAnyAnyMap_LockFunc() { "k4": 4, }) - m.LockFunc(func(m map[interface{}]interface{}) { + m.LockFunc(func(m map[any]any) { totalValue := 0 for _, v := range m { totalValue += v.(int) @@ -559,7 +559,7 @@ func ExampleAnyAnyMap_RLockFunc() { "k4": 4, }) - m.RLockFunc(func(m map[interface{}]interface{}) { + m.RLockFunc(func(m map[any]any) { totalValue := 0 for _, v := range m { totalValue += v.(int) diff --git a/container/gmap/gmap_z_example_int_any_test.go b/container/gmap/gmap_z_example_int_any_test.go index 92f7418b687..14201c7a135 100644 --- a/container/gmap/gmap_z_example_int_any_test.go +++ b/container/gmap/gmap_z_example_int_any_test.go @@ -22,7 +22,7 @@ func ExampleIntAnyMap_Iterator() { } var totalKey, totalValue int - m.Iterator(func(k int, v interface{}) bool { + m.Iterator(func(k int, v any) bool { totalKey += k totalValue += v.(int) @@ -149,7 +149,7 @@ func ExampleIntAnyMap_Set() { func ExampleIntAnyMap_Sets() { m := gmap.NewIntAnyMap() - addMap := make(map[int]interface{}) + addMap := make(map[int]any) addMap[1] = "val1" addMap[2] = "val2" addMap[3] = "val3" @@ -252,10 +252,10 @@ func ExampleIntAnyMap_GetOrSetFunc() { m := gmap.NewIntAnyMap() m.Set(1, "val1") - fmt.Println(m.GetOrSetFunc(1, func() interface{} { + fmt.Println(m.GetOrSetFunc(1, func() any { return "NotExistValue" })) - fmt.Println(m.GetOrSetFunc(2, func() interface{} { + fmt.Println(m.GetOrSetFunc(2, func() any { return "NotExistValue" })) @@ -268,10 +268,10 @@ func ExampleIntAnyMap_GetOrSetFuncLock() { m := gmap.NewIntAnyMap() m.Set(1, "val1") - fmt.Println(m.GetOrSetFuncLock(1, func() interface{} { + fmt.Println(m.GetOrSetFuncLock(1, func() any { return "NotExistValue" })) - fmt.Println(m.GetOrSetFuncLock(2, func() interface{} { + fmt.Println(m.GetOrSetFuncLock(2, func() any { return "NotExistValue" })) @@ -308,10 +308,10 @@ func ExampleIntAnyMap_GetVarOrSetFunc() { m := gmap.NewIntAnyMap() m.Set(1, "val1") - fmt.Println(m.GetVarOrSetFunc(1, func() interface{} { + fmt.Println(m.GetVarOrSetFunc(1, func() any { return "NotExistValue" })) - fmt.Println(m.GetVarOrSetFunc(2, func() interface{} { + fmt.Println(m.GetVarOrSetFunc(2, func() any { return "NotExistValue" })) @@ -324,10 +324,10 @@ func ExampleIntAnyMap_GetVarOrSetFuncLock() { m := gmap.NewIntAnyMap() m.Set(1, "val1") - fmt.Println(m.GetVarOrSetFuncLock(1, func() interface{} { + fmt.Println(m.GetVarOrSetFuncLock(1, func() any { return "NotExistValue" })) - fmt.Println(m.GetVarOrSetFuncLock(2, func() interface{} { + fmt.Println(m.GetVarOrSetFuncLock(2, func() any { return "NotExistValue" })) @@ -350,10 +350,10 @@ func ExampleIntAnyMap_SetIfNotExist() { func ExampleIntAnyMap_SetIfNotExistFunc() { var m gmap.IntAnyMap - fmt.Println(m.SetIfNotExistFunc(1, func() interface{} { + fmt.Println(m.SetIfNotExistFunc(1, func() any { return "v1" })) - fmt.Println(m.SetIfNotExistFunc(1, func() interface{} { + fmt.Println(m.SetIfNotExistFunc(1, func() any { return "v2" })) fmt.Println(m.Map()) @@ -366,10 +366,10 @@ func ExampleIntAnyMap_SetIfNotExistFunc() { func ExampleIntAnyMap_SetIfNotExistFuncLock() { var m gmap.IntAnyMap - fmt.Println(m.SetIfNotExistFuncLock(1, func() interface{} { + fmt.Println(m.SetIfNotExistFuncLock(1, func() any { return "v1" })) - fmt.Println(m.SetIfNotExistFuncLock(1, func() interface{} { + fmt.Println(m.SetIfNotExistFuncLock(1, func() any { return "v2" })) fmt.Println(m.Map()) @@ -538,7 +538,7 @@ func ExampleIntAnyMap_LockFunc() { 4: 4, }) - m.LockFunc(func(m map[int]interface{}) { + m.LockFunc(func(m map[int]any) { totalValue := 0 for _, v := range m { totalValue += v.(int) @@ -559,7 +559,7 @@ func ExampleIntAnyMap_RLockFunc() { 4: 4, }) - m.RLockFunc(func(m map[int]interface{}) { + m.RLockFunc(func(m map[int]any) { totalValue := 0 for _, v := range m { totalValue += v.(int) @@ -651,7 +651,7 @@ func ExampleIntAnyMap_UnmarshalJSON() { func ExampleIntAnyMap_UnmarshalValue() { var m gmap.IntAnyMap - goWeb := map[int]interface{}{ + goWeb := map[int]any{ 1: "goframe", 2: "gin", 3: "echo", diff --git a/container/gmap/gmap_z_example_list_test.go b/container/gmap/gmap_z_example_list_test.go index 8e935fc524d..36f57833a7a 100644 --- a/container/gmap/gmap_z_example_list_test.go +++ b/container/gmap/gmap_z_example_list_test.go @@ -22,7 +22,7 @@ func ExampleListMap_Iterator() { } var totalKey, totalValue int - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { totalKey += k.(int) totalValue += v.(int) @@ -44,7 +44,7 @@ func ExampleListMap_IteratorAsc() { } var totalKey, totalValue int - m.IteratorAsc(func(k interface{}, v interface{}) bool { + m.IteratorAsc(func(k any, v any) bool { totalKey += k.(int) totalValue += v.(int) @@ -66,7 +66,7 @@ func ExampleListMap_IteratorDesc() { } var totalKey, totalValue int - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { totalKey += k.(int) totalValue += v.(int) @@ -188,7 +188,7 @@ func ExampleListMap_Set() { func ExampleListMap_Sets() { m := gmap.NewListMap() - addMap := make(map[interface{}]interface{}) + addMap := make(map[any]any) addMap["key1"] = "val1" addMap["key2"] = "val2" addMap["key3"] = "val3" @@ -291,10 +291,10 @@ func ExampleListMap_GetOrSetFunc() { m := gmap.NewListMap() m.Set("key1", "val1") - fmt.Println(m.GetOrSetFunc("key1", func() interface{} { + fmt.Println(m.GetOrSetFunc("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetOrSetFunc("key2", func() interface{} { + fmt.Println(m.GetOrSetFunc("key2", func() any { return "NotExistValue" })) @@ -307,10 +307,10 @@ func ExampleListMap_GetOrSetFuncLock() { m := gmap.NewListMap() m.Set("key1", "val1") - fmt.Println(m.GetOrSetFuncLock("key1", func() interface{} { + fmt.Println(m.GetOrSetFuncLock("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetOrSetFuncLock("key2", func() interface{} { + fmt.Println(m.GetOrSetFuncLock("key2", func() any { return "NotExistValue" })) @@ -347,10 +347,10 @@ func ExampleListMap_GetVarOrSetFunc() { m := gmap.NewListMap() m.Set("key1", "val1") - fmt.Println(m.GetVarOrSetFunc("key1", func() interface{} { + fmt.Println(m.GetVarOrSetFunc("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetVarOrSetFunc("key2", func() interface{} { + fmt.Println(m.GetVarOrSetFunc("key2", func() any { return "NotExistValue" })) @@ -363,10 +363,10 @@ func ExampleListMap_GetVarOrSetFuncLock() { m := gmap.NewListMap() m.Set("key1", "val1") - fmt.Println(m.GetVarOrSetFuncLock("key1", func() interface{} { + fmt.Println(m.GetVarOrSetFuncLock("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetVarOrSetFuncLock("key2", func() interface{} { + fmt.Println(m.GetVarOrSetFuncLock("key2", func() any { return "NotExistValue" })) @@ -389,10 +389,10 @@ func ExampleListMap_SetIfNotExist() { func ExampleListMap_SetIfNotExistFunc() { var m gmap.ListMap - fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFunc("k1", func() any { return "v1" })) - fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFunc("k1", func() any { return "v2" })) fmt.Println(m.Map()) @@ -405,10 +405,10 @@ func ExampleListMap_SetIfNotExistFunc() { func ExampleListMap_SetIfNotExistFuncLock() { var m gmap.ListMap - fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFuncLock("k1", func() any { return "v1" })) - fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFuncLock("k1", func() any { return "v2" })) fmt.Println(m.Map()) @@ -442,7 +442,7 @@ func ExampleListMap_Removes() { "k4": "v4", }) - removeList := make([]interface{}, 2) + removeList := make([]any, 2) removeList = append(removeList, "k1") removeList = append(removeList, "k2") diff --git a/container/gmap/gmap_z_example_str_any_test.go b/container/gmap/gmap_z_example_str_any_test.go index a71adaaaba3..0571befa8b6 100644 --- a/container/gmap/gmap_z_example_str_any_test.go +++ b/container/gmap/gmap_z_example_str_any_test.go @@ -22,7 +22,7 @@ func ExampleStrAnyMap_Iterator() { } var totalValue int - m.Iterator(func(k string, v interface{}) bool { + m.Iterator(func(k string, v any) bool { totalValue += v.(int) return totalValue < 50 @@ -146,7 +146,7 @@ func ExampleStrAnyMap_Set() { func ExampleStrAnyMap_Sets() { m := gmap.NewStrAnyMap() - addMap := make(map[string]interface{}) + addMap := make(map[string]any) addMap["key1"] = "val1" addMap["key2"] = "val2" addMap["key3"] = "val3" @@ -249,10 +249,10 @@ func ExampleStrAnyMap_GetOrSetFunc() { m := gmap.NewStrAnyMap() m.Set("key1", "val1") - fmt.Println(m.GetOrSetFunc("key1", func() interface{} { + fmt.Println(m.GetOrSetFunc("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetOrSetFunc("key2", func() interface{} { + fmt.Println(m.GetOrSetFunc("key2", func() any { return "NotExistValue" })) @@ -265,10 +265,10 @@ func ExampleStrAnyMap_GetOrSetFuncLock() { m := gmap.NewStrAnyMap() m.Set("key1", "val1") - fmt.Println(m.GetOrSetFuncLock("key1", func() interface{} { + fmt.Println(m.GetOrSetFuncLock("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetOrSetFuncLock("key2", func() interface{} { + fmt.Println(m.GetOrSetFuncLock("key2", func() any { return "NotExistValue" })) @@ -305,10 +305,10 @@ func ExampleStrAnyMap_GetVarOrSetFunc() { m := gmap.NewStrAnyMap() m.Set("key1", "val1") - fmt.Println(m.GetVarOrSetFunc("key1", func() interface{} { + fmt.Println(m.GetVarOrSetFunc("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetVarOrSetFunc("key2", func() interface{} { + fmt.Println(m.GetVarOrSetFunc("key2", func() any { return "NotExistValue" })) @@ -321,10 +321,10 @@ func ExampleStrAnyMap_GetVarOrSetFuncLock() { m := gmap.NewStrAnyMap() m.Set("key1", "val1") - fmt.Println(m.GetVarOrSetFuncLock("key1", func() interface{} { + fmt.Println(m.GetVarOrSetFuncLock("key1", func() any { return "NotExistValue" })) - fmt.Println(m.GetVarOrSetFuncLock("key2", func() interface{} { + fmt.Println(m.GetVarOrSetFuncLock("key2", func() any { return "NotExistValue" })) @@ -347,10 +347,10 @@ func ExampleStrAnyMap_SetIfNotExist() { func ExampleStrAnyMap_SetIfNotExistFunc() { var m gmap.StrAnyMap - fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFunc("k1", func() any { return "v1" })) - fmt.Println(m.SetIfNotExistFunc("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFunc("k1", func() any { return "v2" })) fmt.Println(m.Map()) @@ -363,10 +363,10 @@ func ExampleStrAnyMap_SetIfNotExistFunc() { func ExampleStrAnyMap_SetIfNotExistFuncLock() { var m gmap.StrAnyMap - fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFuncLock("k1", func() any { return "v1" })) - fmt.Println(m.SetIfNotExistFuncLock("k1", func() interface{} { + fmt.Println(m.SetIfNotExistFuncLock("k1", func() any { return "v2" })) fmt.Println(m.Map()) @@ -535,7 +535,7 @@ func ExampleStrAnyMap_LockFunc() { "k4": 4, }) - m.LockFunc(func(m map[string]interface{}) { + m.LockFunc(func(m map[string]any) { totalValue := 0 for _, v := range m { totalValue += v.(int) @@ -556,7 +556,7 @@ func ExampleStrAnyMap_RLockFunc() { "k4": 4, }) - m.RLockFunc(func(m map[string]interface{}) { + m.RLockFunc(func(m map[string]any) { totalValue := 0 for _, v := range m { totalValue += v.(int) @@ -648,7 +648,7 @@ func ExampleStrAnyMap_UnmarshalJSON() { func ExampleStrAnyMap_UnmarshalValue() { var m gmap.StrAnyMap - goWeb := map[string]interface{}{ + goWeb := map[string]any{ "goframe": "https://goframe.org", "gin": "https://gin-gonic.com/", "echo": "https://echo.labstack.com/", diff --git a/container/gmap/gmap_z_example_test.go b/container/gmap/gmap_z_example_test.go index 0acee4ab95c..b88da67e924 100644 --- a/container/gmap/gmap_z_example_test.go +++ b/container/gmap/gmap_z_example_test.go @@ -22,7 +22,7 @@ func ExampleNew() { // Print size. fmt.Println(m.Size()) - addMap := make(map[interface{}]interface{}) + addMap := make(map[any]any) addMap["key2"] = "val2" addMap["key3"] = "val3" addMap[1] = 1 @@ -46,7 +46,7 @@ func ExampleNew() { fmt.Println(m.Keys()) // Batch remove keys. - m.Removes([]interface{}{"key1", 1}) + m.Removes([]any{"key1", 1}) fmt.Println(m.Keys()) // Contains checks whether a key exists. diff --git a/container/gmap/gmap_z_unit_hash_any_any_test.go b/container/gmap/gmap_z_unit_hash_any_any_test.go index 57be564d15c..9665db1b8aa 100644 --- a/container/gmap/gmap_z_unit_hash_any_any_test.go +++ b/container/gmap/gmap_z_unit_hash_any_any_test.go @@ -40,7 +40,7 @@ func Test_AnyAnyMap_Var(t *testing.T) { t.AssertIN(3, m.Values()) t.AssertIN(1, m.Values()) m.Flip() - t.Assert(m.Map(), map[interface{}]int{1: 1, 3: 3}) + t.Assert(m.Map(), map[any]int{1: 1, 3: 3}) m.Clear() t.Assert(m.Size(), 0) @@ -70,14 +70,14 @@ func Test_AnyAnyMap_Basic(t *testing.T) { t.AssertIN(3, m.Values()) t.AssertIN(1, m.Values()) m.Flip() - t.Assert(m.Map(), map[interface{}]int{1: 1, 3: 3}) + t.Assert(m.Map(), map[any]int{1: 1, 3: 3}) m.Clear() t.Assert(m.Size(), 0) t.Assert(m.IsEmpty(), true) - m2 := gmap.NewAnyAnyMapFrom(map[interface{}]interface{}{1: 1, 2: "2"}) - t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, 2: "2"}) + m2 := gmap.NewAnyAnyMapFrom(map[any]any{1: 1, 2: "2"}) + t.Assert(m2.Map(), map[any]any{1: 1, 2: "2"}) }) } @@ -103,23 +103,23 @@ func Test_AnyAnyMap_Batch(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gmap.NewAnyAnyMap() - m.Sets(map[interface{}]interface{}{1: 1, 2: "2", 3: 3}) - t.Assert(m.Map(), map[interface{}]interface{}{1: 1, 2: "2", 3: 3}) - m.Removes([]interface{}{1, 2}) - t.Assert(m.Map(), map[interface{}]interface{}{3: 3}) + m.Sets(map[any]any{1: 1, 2: "2", 3: 3}) + t.Assert(m.Map(), map[any]any{1: 1, 2: "2", 3: 3}) + m.Removes([]any{1, 2}) + t.Assert(m.Map(), map[any]any{3: 3}) }) } func Test_AnyAnyMap_Iterator_Deadlock(t *testing.T) { gtest.C(t, func(t *gtest.T) { - m := gmap.NewAnyAnyMapFrom(map[interface{}]interface{}{1: 1, 2: "2", "3": "3", "4": 4}, true) - m.Iterator(func(k interface{}, _ interface{}) bool { + m := gmap.NewAnyAnyMapFrom(map[any]any{1: 1, 2: "2", "3": "3", "4": 4}, true) + m.Iterator(func(k any, _ any) bool { if gconv.Int(k)%2 == 0 { m.Remove(k) } return true }) - t.Assert(m.Map(), map[interface{}]interface{}{ + t.Assert(m.Map(), map[any]any{ 1: 1, "3": "3", }) @@ -128,20 +128,20 @@ func Test_AnyAnyMap_Iterator_Deadlock(t *testing.T) { func Test_AnyAnyMap_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[interface{}]interface{}{1: 1, 2: "2"} + expect := map[any]any{1: 1, 2: "2"} m := gmap.NewAnyAnyMapFrom(expect) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { t.Assert(expect[k], v) return true }) // 断言返回值对遍历控制 i := 0 j := 0 - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { i++ return true }) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { j++ return false }) @@ -152,12 +152,12 @@ func Test_AnyAnyMap_Iterator(t *testing.T) { func Test_AnyAnyMap_Lock(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[interface{}]interface{}{1: 1, 2: "2"} + expect := map[any]any{1: 1, 2: "2"} m := gmap.NewAnyAnyMapFrom(expect) - m.LockFunc(func(m map[interface{}]interface{}) { + m.LockFunc(func(m map[any]any) { t.Assert(m, expect) }) - m.RLockFunc(func(m map[interface{}]interface{}) { + m.RLockFunc(func(m map[any]any) { t.Assert(m, expect) }) }) @@ -166,7 +166,7 @@ func Test_AnyAnyMap_Lock(t *testing.T) { func Test_AnyAnyMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { // clone 方法是深克隆 - m := gmap.NewAnyAnyMapFrom(map[interface{}]interface{}{1: 1, 2: "2"}) + m := gmap.NewAnyAnyMapFrom(map[any]any{1: 1, 2: "2"}) m_clone := m.Clone() m.Remove(1) @@ -186,7 +186,7 @@ func Test_AnyAnyMap_Merge(t *testing.T) { m1.Set(1, 1) m2.Set(2, "2") m1.Merge(m2) - t.Assert(m1.Map(), map[interface{}]interface{}{1: 1, 2: "2"}) + t.Assert(m1.Map(), map[any]any{1: 1, 2: "2"}) m3 := gmap.NewAnyAnyMapFrom(nil) m3.Merge(m2) t.Assert(m3.Map(), m2.Map()) @@ -366,7 +366,7 @@ func TestAnyAnyMap_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": []byte(`{"k1":"v1","k2":"v2"}`), }, &v) @@ -379,7 +379,7 @@ func TestAnyAnyMap_UnmarshalValue(t *testing.T) { // Map gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": g.Map{ "k1": "v1", @@ -438,8 +438,8 @@ func Test_AnyAnyMap_Diff(t *testing.T) { 4: "v4", }) addedKeys, removedKeys, updatedKeys := m1.Diff(m2) - t.Assert(addedKeys, []interface{}{4}) - t.Assert(removedKeys, []interface{}{"1"}) - t.Assert(updatedKeys, []interface{}{3}) + t.Assert(addedKeys, []any{4}) + t.Assert(removedKeys, []any{"1"}) + t.Assert(updatedKeys, []any{3}) }) } diff --git a/container/gmap/gmap_z_unit_hash_int_any_test.go b/container/gmap/gmap_z_unit_hash_int_any_test.go index b731054114c..7c2f1731461 100644 --- a/container/gmap/gmap_z_unit_hash_int_any_test.go +++ b/container/gmap/gmap_z_unit_hash_int_any_test.go @@ -17,7 +17,7 @@ import ( "github.com/gogf/gf/v2/util/gconv" ) -func getAny() interface{} { +func getAny() any { return 123 } @@ -43,7 +43,7 @@ func Test_IntAnyMap_Var(t *testing.T) { t.AssertIN(3, m.Values()) t.AssertIN(1, m.Values()) m.Flip() - t.Assert(m.Map(), map[interface{}]int{1: 1, 3: 3}) + t.Assert(m.Map(), map[any]int{1: 1, 3: 3}) m.Clear() t.Assert(m.Size(), 0) @@ -73,20 +73,20 @@ func Test_IntAnyMap_Basic(t *testing.T) { t.AssertIN(3, m.Values()) t.AssertIN(1, m.Values()) m.Flip() - t.Assert(m.Map(), map[interface{}]int{1: 1, 3: 3}) + t.Assert(m.Map(), map[any]int{1: 1, 3: 3}) m.Clear() t.Assert(m.Size(), 0) t.Assert(m.IsEmpty(), true) - m2 := gmap.NewIntAnyMapFrom(map[int]interface{}{1: 1, 2: "2"}) - t.Assert(m2.Map(), map[int]interface{}{1: 1, 2: "2"}) + m2 := gmap.NewIntAnyMapFrom(map[int]any{1: 1, 2: "2"}) + t.Assert(m2.Map(), map[int]any{1: 1, 2: "2"}) }) gtest.C(t, func(t *gtest.T) { m := gmap.NewIntAnyMap(true) m.Set(1, 1) - t.Assert(m.Map(), map[int]interface{}{1: 1}) + t.Assert(m.Map(), map[int]any{1: 1}) }) } @@ -111,23 +111,23 @@ func Test_IntAnyMap_Batch(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gmap.NewIntAnyMap() - m.Sets(map[int]interface{}{1: 1, 2: "2", 3: 3}) - t.Assert(m.Map(), map[int]interface{}{1: 1, 2: "2", 3: 3}) + m.Sets(map[int]any{1: 1, 2: "2", 3: 3}) + t.Assert(m.Map(), map[int]any{1: 1, 2: "2", 3: 3}) m.Removes([]int{1, 2}) - t.Assert(m.Map(), map[int]interface{}{3: 3}) + t.Assert(m.Map(), map[int]any{3: 3}) }) } func Test_IntAnyMap_Iterator_Deadlock(t *testing.T) { gtest.C(t, func(t *gtest.T) { - m := gmap.NewIntAnyMapFrom(map[int]interface{}{1: 1, 2: 2, 3: "3", 4: 4}, true) - m.Iterator(func(k int, _ interface{}) bool { + m := gmap.NewIntAnyMapFrom(map[int]any{1: 1, 2: 2, 3: "3", 4: 4}, true) + m.Iterator(func(k int, _ any) bool { if k%2 == 0 { m.Remove(k) } return true }) - t.Assert(m.Map(), map[int]interface{}{ + t.Assert(m.Map(), map[int]any{ 1: 1, 3: "3", }) @@ -136,20 +136,20 @@ func Test_IntAnyMap_Iterator_Deadlock(t *testing.T) { func Test_IntAnyMap_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[int]interface{}{1: 1, 2: "2"} + expect := map[int]any{1: 1, 2: "2"} m := gmap.NewIntAnyMapFrom(expect) - m.Iterator(func(k int, v interface{}) bool { + m.Iterator(func(k int, v any) bool { t.Assert(expect[k], v) return true }) // 断言返回值对遍历控制 i := 0 j := 0 - m.Iterator(func(k int, v interface{}) bool { + m.Iterator(func(k int, v any) bool { i++ return true }) - m.Iterator(func(k int, v interface{}) bool { + m.Iterator(func(k int, v any) bool { j++ return false }) @@ -161,12 +161,12 @@ func Test_IntAnyMap_Iterator(t *testing.T) { func Test_IntAnyMap_Lock(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[int]interface{}{1: 1, 2: "2"} + expect := map[int]any{1: 1, 2: "2"} m := gmap.NewIntAnyMapFrom(expect) - m.LockFunc(func(m map[int]interface{}) { + m.LockFunc(func(m map[int]any) { t.Assert(m, expect) }) - m.RLockFunc(func(m map[int]interface{}) { + m.RLockFunc(func(m map[int]any) { t.Assert(m, expect) }) }) @@ -175,7 +175,7 @@ func Test_IntAnyMap_Lock(t *testing.T) { func Test_IntAnyMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { // clone 方法是深克隆 - m := gmap.NewIntAnyMapFrom(map[int]interface{}{1: 1, 2: "2"}) + m := gmap.NewIntAnyMapFrom(map[int]any{1: 1, 2: "2"}) m_clone := m.Clone() m.Remove(1) @@ -195,7 +195,7 @@ func Test_IntAnyMap_Merge(t *testing.T) { m1.Set(1, 1) m2.Set(2, "2") m1.Merge(m2) - t.Assert(m1.Map(), map[int]interface{}{1: 1, 2: "2"}) + t.Assert(m1.Map(), map[int]any{1: 1, 2: "2"}) m3 := gmap.NewIntAnyMapFrom(nil) m3.Merge(m2) t.Assert(m3.Map(), m2.Map()) @@ -350,7 +350,7 @@ func TestIntAnyMap_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": []byte(`{"1":"v1","2":"v2"}`), }, &v) @@ -363,7 +363,7 @@ func TestIntAnyMap_UnmarshalValue(t *testing.T) { // Map gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": g.MapIntAny{ 1: "v1", diff --git a/container/gmap/gmap_z_unit_hash_int_int_test.go b/container/gmap/gmap_z_unit_hash_int_int_test.go index 4676aeee33d..0d352725e94 100644 --- a/container/gmap/gmap_z_unit_hash_int_int_test.go +++ b/container/gmap/gmap_z_unit_hash_int_int_test.go @@ -358,7 +358,7 @@ func TestIntIntMap_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": []byte(`{"1":1,"2":2}`), }, &v) @@ -371,7 +371,7 @@ func TestIntIntMap_UnmarshalValue(t *testing.T) { // Map gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": g.MapIntAny{ 1: 1, diff --git a/container/gmap/gmap_z_unit_hash_int_str_test.go b/container/gmap/gmap_z_unit_hash_int_str_test.go index 96557ac0ada..36ae4de0a77 100644 --- a/container/gmap/gmap_z_unit_hash_int_str_test.go +++ b/container/gmap/gmap_z_unit_hash_int_str_test.go @@ -149,7 +149,7 @@ func Test_IntStrMap_Batch(t *testing.T) { m.Sets(map[int]string{1: "a", 2: "b", 3: "c"}) t.Assert(m.Map(), map[int]string{1: "a", 2: "b", 3: "c"}) m.Removes([]int{1, 2}) - t.Assert(m.Map(), map[int]interface{}{3: "c"}) + t.Assert(m.Map(), map[int]any{3: "c"}) }) } @@ -384,7 +384,7 @@ func TestIntStrMap_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": []byte(`{"1":"v1","2":"v2"}`), }, &v) @@ -397,7 +397,7 @@ func TestIntStrMap_UnmarshalValue(t *testing.T) { // Map gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": g.MapIntAny{ 1: "v1", diff --git a/container/gmap/gmap_z_unit_hash_str_any_test.go b/container/gmap/gmap_z_unit_hash_str_any_test.go index 70e6f1d8343..dcf34aa37d5 100644 --- a/container/gmap/gmap_z_unit_hash_str_any_test.go +++ b/container/gmap/gmap_z_unit_hash_str_any_test.go @@ -41,7 +41,7 @@ func Test_StrAnyMap_Var(t *testing.T) { t.AssertIN(1, m.Values()) m.Flip() - t.Assert(m.Map(), map[string]interface{}{"1": "a", "3": "c"}) + t.Assert(m.Map(), map[string]any{"1": "a", "3": "c"}) m.Clear() t.Assert(m.Size(), 0) @@ -72,14 +72,14 @@ func Test_StrAnyMap_Basic(t *testing.T) { t.AssertIN(1, m.Values()) m.Flip() - t.Assert(m.Map(), map[string]interface{}{"1": "a", "3": "c"}) + t.Assert(m.Map(), map[string]any{"1": "a", "3": "c"}) m.Clear() t.Assert(m.Size(), 0) t.Assert(m.IsEmpty(), true) - m2 := gmap.NewStrAnyMapFrom(map[string]interface{}{"a": 1, "b": "2"}) - t.Assert(m2.Map(), map[string]interface{}{"a": 1, "b": "2"}) + m2 := gmap.NewStrAnyMapFrom(map[string]any{"a": 1, "b": "2"}) + t.Assert(m2.Map(), map[string]any{"a": 1, "b": "2"}) }) } @@ -103,24 +103,24 @@ func Test_StrAnyMap_Batch(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gmap.NewStrAnyMap() - m.Sets(map[string]interface{}{"a": 1, "b": "2", "c": 3}) - t.Assert(m.Map(), map[string]interface{}{"a": 1, "b": "2", "c": 3}) + m.Sets(map[string]any{"a": 1, "b": "2", "c": 3}) + t.Assert(m.Map(), map[string]any{"a": 1, "b": "2", "c": 3}) m.Removes([]string{"a", "b"}) - t.Assert(m.Map(), map[string]interface{}{"c": 3}) + t.Assert(m.Map(), map[string]any{"c": 3}) }) } func Test_StrAnyMap_Iterator_Deadlock(t *testing.T) { gtest.C(t, func(t *gtest.T) { - m := gmap.NewStrAnyMapFrom(map[string]interface{}{"1": "1", "2": "2", "3": "3", "4": "4"}, true) - m.Iterator(func(k string, _ interface{}) bool { + m := gmap.NewStrAnyMapFrom(map[string]any{"1": "1", "2": "2", "3": "3", "4": "4"}, true) + m.Iterator(func(k string, _ any) bool { kInt, _ := strconv.Atoi(k) if kInt%2 == 0 { m.Remove(k) } return true }) - t.Assert(m.Map(), map[string]interface{}{ + t.Assert(m.Map(), map[string]any{ "1": "1", "3": "3", }) @@ -129,20 +129,20 @@ func Test_StrAnyMap_Iterator_Deadlock(t *testing.T) { func Test_StrAnyMap_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[string]interface{}{"a": true, "b": false} + expect := map[string]any{"a": true, "b": false} m := gmap.NewStrAnyMapFrom(expect) - m.Iterator(func(k string, v interface{}) bool { + m.Iterator(func(k string, v any) bool { t.Assert(expect[k], v) return true }) // 断言返回值对遍历控制 i := 0 j := 0 - m.Iterator(func(k string, v interface{}) bool { + m.Iterator(func(k string, v any) bool { i++ return true }) - m.Iterator(func(k string, v interface{}) bool { + m.Iterator(func(k string, v any) bool { j++ return false }) @@ -153,13 +153,13 @@ func Test_StrAnyMap_Iterator(t *testing.T) { func Test_StrAnyMap_Lock(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[string]interface{}{"a": true, "b": false} + expect := map[string]any{"a": true, "b": false} m := gmap.NewStrAnyMapFrom(expect) - m.LockFunc(func(m map[string]interface{}) { + m.LockFunc(func(m map[string]any) { t.Assert(m, expect) }) - m.RLockFunc(func(m map[string]interface{}) { + m.RLockFunc(func(m map[string]any) { t.Assert(m, expect) }) }) @@ -168,7 +168,7 @@ func Test_StrAnyMap_Lock(t *testing.T) { func Test_StrAnyMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { // clone 方法是深克隆 - m := gmap.NewStrAnyMapFrom(map[string]interface{}{"a": 1, "b": "2"}) + m := gmap.NewStrAnyMapFrom(map[string]any{"a": 1, "b": "2"}) m_clone := m.Clone() m.Remove("a") @@ -188,7 +188,7 @@ func Test_StrAnyMap_Merge(t *testing.T) { m1.Set("a", 1) m2.Set("b", "2") m1.Merge(m2) - t.Assert(m1.Map(), map[string]interface{}{"a": 1, "b": "2"}) + t.Assert(m1.Map(), map[string]any{"a": 1, "b": "2"}) m3 := gmap.NewStrAnyMapFrom(nil) m3.Merge(m2) @@ -358,7 +358,7 @@ func TestStrAnyMap_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": []byte(`{"k1":"v1","k2":"v2"}`), }, &v) @@ -371,7 +371,7 @@ func TestStrAnyMap_UnmarshalValue(t *testing.T) { // Map gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": g.Map{ "k1": "v1", diff --git a/container/gmap/gmap_z_unit_hash_str_int_test.go b/container/gmap/gmap_z_unit_hash_str_int_test.go index 6ae53adc83b..577eff1e112 100644 --- a/container/gmap/gmap_z_unit_hash_str_int_test.go +++ b/container/gmap/gmap_z_unit_hash_str_int_test.go @@ -363,7 +363,7 @@ func TestStrIntMap_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": []byte(`{"k1":1,"k2":2}`), }, &v) @@ -376,7 +376,7 @@ func TestStrIntMap_UnmarshalValue(t *testing.T) { // Map gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": g.Map{ "k1": 1, diff --git a/container/gmap/gmap_z_unit_hash_str_str_test.go b/container/gmap/gmap_z_unit_hash_str_str_test.go index ffa76b32939..7cbd4fbb634 100644 --- a/container/gmap/gmap_z_unit_hash_str_str_test.go +++ b/container/gmap/gmap_z_unit_hash_str_str_test.go @@ -362,7 +362,7 @@ func TestStrStrMap_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": []byte(`{"k1":"v1","k2":"v2"}`), }, &v) @@ -375,7 +375,7 @@ func TestStrStrMap_UnmarshalValue(t *testing.T) { // Map gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": g.Map{ "k1": "v1", diff --git a/container/gmap/gmap_z_unit_list_map_test.go b/container/gmap/gmap_z_unit_list_map_test.go index e1fe7099b6e..c8a6074bfae 100644 --- a/container/gmap/gmap_z_unit_list_map_test.go +++ b/container/gmap/gmap_z_unit_list_map_test.go @@ -21,7 +21,7 @@ func Test_ListMap_Var(t *testing.T) { gtest.C(t, func(t *gtest.T) { var m gmap.ListMap m.Set("key1", "val1") - t.Assert(m.Keys(), []interface{}{"key1"}) + t.Assert(m.Keys(), []any{"key1"}) t.Assert(m.Get("key1"), "val1") t.Assert(m.Size(), 1) @@ -41,7 +41,7 @@ func Test_ListMap_Var(t *testing.T) { m.Flip() - t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) + t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"}) m.Clear() t.Assert(m.Size(), 0) @@ -53,7 +53,7 @@ func Test_ListMap_Basic(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gmap.NewListMap() m.Set("key1", "val1") - t.Assert(m.Keys(), []interface{}{"key1"}) + t.Assert(m.Keys(), []any{"key1"}) t.Assert(m.Get("key1"), "val1") t.Assert(m.Size(), 1) @@ -73,14 +73,14 @@ func Test_ListMap_Basic(t *testing.T) { m.Flip() - t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) + t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"}) m.Clear() t.Assert(m.Size(), 0) t.Assert(m.IsEmpty(), true) - m2 := gmap.NewListMapFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) - t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, "key1": "val1"}) + m2 := gmap.NewListMapFrom(map[any]any{1: 1, "key1": "val1"}) + t.Assert(m2.Map(), map[any]any{1: 1, "key1": "val1"}) }) } @@ -100,30 +100,30 @@ func Test_ListMap_Set_Fun(t *testing.T) { func Test_ListMap_Batch(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gmap.NewListMap() - m.Sets(map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - t.Assert(m.Map(), map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - m.Removes([]interface{}{"key1", 1}) - t.Assert(m.Map(), map[interface{}]interface{}{"key2": "val2", "key3": "val3"}) + m.Sets(map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + t.Assert(m.Map(), map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + m.Removes([]any{"key1", 1}) + t.Assert(m.Map(), map[any]any{"key2": "val2", "key3": "val3"}) }) } func Test_ListMap_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[interface{}]interface{}{1: 1, "key1": "val1"} + expect := map[any]any{1: 1, "key1": "val1"} m := gmap.NewListMapFrom(expect) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { t.Assert(expect[k], v) return true }) // 断言返回值对遍历控制 i := 0 j := 0 - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { i++ return true }) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { j++ return false }) @@ -135,7 +135,7 @@ func Test_ListMap_Iterator(t *testing.T) { func Test_ListMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { // clone 方法是深克隆 - m := gmap.NewListMapFrom(map[interface{}]interface{}{1: 1, "key1": "val1"}) + m := gmap.NewListMapFrom(map[any]any{1: 1, "key1": "val1"}) m_clone := m.Clone() m.Remove(1) // 修改原 map,clone 后的 map 不影响 @@ -154,7 +154,7 @@ func Test_ListMap_Basic_Merge(t *testing.T) { m1.Set("key1", "val1") m2.Set("key2", "val2") m1.Merge(m2) - t.Assert(m1.Map(), map[interface{}]interface{}{"key1": "val1", "key2": "val2"}) + t.Assert(m1.Map(), map[any]any{"key1": "val1", "key2": "val2"}) m3 := gmap.NewListMapFrom(nil) m3.Merge(m2) t.Assert(m3.Map(), m2.Map()) @@ -321,7 +321,7 @@ func TestListMap_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": []byte(`{"1":"v1","2":"v2"}`), }, &v) @@ -334,7 +334,7 @@ func TestListMap_UnmarshalValue(t *testing.T) { // Map gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": g.MapIntAny{ 1: "v1", diff --git a/container/gmap/gmap_z_unit_tree_map_test.go b/container/gmap/gmap_z_unit_tree_map_test.go index 67807b47452..741c31286eb 100644 --- a/container/gmap/gmap_z_unit_tree_map_test.go +++ b/container/gmap/gmap_z_unit_tree_map_test.go @@ -22,7 +22,7 @@ func Test_TreeMap_Var(t *testing.T) { var m gmap.TreeMap m.SetComparator(gutil.ComparatorString) m.Set("key1", "val1") - t.Assert(m.Keys(), []interface{}{"key1"}) + t.Assert(m.Keys(), []any{"key1"}) t.Assert(m.Get("key1"), "val1") t.Assert(m.Size(), 1) @@ -42,7 +42,7 @@ func Test_TreeMap_Var(t *testing.T) { t.AssertIN("val1", m.Values()) m.Flip() - t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) + t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"}) m.Clear() t.Assert(m.Size(), 0) @@ -54,7 +54,7 @@ func Test_TreeMap_Basic(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gmap.NewTreeMap(gutil.ComparatorString) m.Set("key1", "val1") - t.Assert(m.Keys(), []interface{}{"key1"}) + t.Assert(m.Keys(), []any{"key1"}) t.Assert(m.Get("key1"), "val1") t.Assert(m.Size(), 1) @@ -74,14 +74,14 @@ func Test_TreeMap_Basic(t *testing.T) { t.AssertIN("val1", m.Values()) m.Flip() - t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) + t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"}) m.Clear() t.Assert(m.Size(), 0) t.Assert(m.IsEmpty(), true) - m2 := gmap.NewTreeMapFrom(gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) - t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, "key1": "val1"}) + m2 := gmap.NewTreeMapFrom(gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"}) + t.Assert(m2.Map(), map[any]any{1: 1, "key1": "val1"}) }) } @@ -101,29 +101,29 @@ func Test_TreeMap_Set_Fun(t *testing.T) { func Test_TreeMap_Batch(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gmap.NewTreeMap(gutil.ComparatorString) - m.Sets(map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - t.Assert(m.Map(), map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - m.Removes([]interface{}{"key1", 1}) - t.Assert(m.Map(), map[interface{}]interface{}{"key2": "val2", "key3": "val3"}) + m.Sets(map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + t.Assert(m.Map(), map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + m.Removes([]any{"key1", 1}) + t.Assert(m.Map(), map[any]any{"key2": "val2", "key3": "val3"}) }) } func Test_TreeMap_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { - expect := map[interface{}]interface{}{1: 1, "key1": "val1"} + expect := map[any]any{1: 1, "key1": "val1"} m := gmap.NewTreeMapFrom(gutil.ComparatorString, expect) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { t.Assert(expect[k], v) return true }) // 断言返回值对遍历控制 i := 0 j := 0 - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { i++ return true }) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { j++ return false }) @@ -132,17 +132,17 @@ func Test_TreeMap_Iterator(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - expect := map[interface{}]interface{}{1: 1, "key1": "val1"} + expect := map[any]any{1: 1, "key1": "val1"} m := gmap.NewTreeMapFrom(gutil.ComparatorString, expect) for i := 0; i < 10; i++ { - m.IteratorAsc(func(k interface{}, v interface{}) bool { + m.IteratorAsc(func(k any, v any) bool { t.Assert(expect[k], v) return true }) } j := 0 for i := 0; i < 10; i++ { - m.IteratorAsc(func(k interface{}, v interface{}) bool { + m.IteratorAsc(func(k any, v any) bool { j++ return false }) @@ -154,7 +154,7 @@ func Test_TreeMap_Iterator(t *testing.T) { func Test_TreeMap_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { // clone 方法是深克隆 - m := gmap.NewTreeMapFrom(gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) + m := gmap.NewTreeMapFrom(gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"}) m_clone := m.Clone() m.Remove(1) // 修改原 map,clone 后的 map 不影响 @@ -218,7 +218,7 @@ func TestTreeMap_UnmarshalValue(t *testing.T) { // JSON gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": []byte(`{"k1":"v1","k2":"v2"}`), }, &v) @@ -231,7 +231,7 @@ func TestTreeMap_UnmarshalValue(t *testing.T) { // Map gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "map": g.Map{ "k1": "v1", diff --git a/container/gpool/gpool.go b/container/gpool/gpool.go index 355853b9ce4..bd432c9e396 100644 --- a/container/gpool/gpool.go +++ b/container/gpool/gpool.go @@ -21,28 +21,28 @@ import ( // Pool is an Object-Reusable Pool. type Pool struct { - list *glist.List // Available/idle items list. - closed *gtype.Bool // Whether the pool is closed. - TTL time.Duration // Time To Live for pool items. - NewFunc func() (interface{}, error) // Callback function to create pool item. + list *glist.List // Available/idle items list. + closed *gtype.Bool // Whether the pool is closed. + TTL time.Duration // Time To Live for pool items. + NewFunc func() (any, error) // Callback function to create pool item. // ExpireFunc is the function for expired items destruction. // This function needs to be defined when the pool items // need to perform additional destruction operations. // Eg: net.Conn, os.File, etc. - ExpireFunc func(interface{}) + ExpireFunc func(any) } // Pool item. type poolItem struct { - value interface{} // Item value. - expireAt int64 // Expire timestamp in milliseconds. + value any // Item value. + expireAt int64 // Expire timestamp in milliseconds. } // NewFunc Creation function for object. -type NewFunc func() (interface{}, error) +type NewFunc func() (any, error) // ExpireFunc Destruction function for object. -type ExpireFunc func(interface{}) +type ExpireFunc func(any) // New creates and returns a new object pool. // To ensure execution efficiency, the expiration time cannot be modified once it is set. @@ -66,7 +66,7 @@ func New(ttl time.Duration, newFunc NewFunc, expireFunc ...ExpireFunc) *Pool { } // Put puts an item to pool. -func (p *Pool) Put(value interface{}) error { +func (p *Pool) Put(value any) error { if p.closed.Val() { return gerror.NewCode(gcode.CodeInvalidOperation, "pool is closed") } @@ -85,7 +85,7 @@ func (p *Pool) Put(value interface{}) error { } // MustPut puts an item to pool, it panics if any error occurs. -func (p *Pool) MustPut(value interface{}) { +func (p *Pool) MustPut(value any) { if err := p.Put(value); err != nil { panic(err) } @@ -108,7 +108,7 @@ func (p *Pool) Clear() { // Get picks and returns an item from pool. If the pool is empty and NewFunc is defined, // it creates and returns one from NewFunc. -func (p *Pool) Get() (interface{}, error) { +func (p *Pool) Get() (any, error) { for !p.closed.Val() { if r := p.list.PopFront(); r != nil { f := r.(*poolItem) diff --git a/container/gpool/gpool_z_example_test.go b/container/gpool/gpool_z_example_test.go index 54509c8391a..8077128edd8 100644 --- a/container/gpool/gpool_z_example_test.go +++ b/container/gpool/gpool_z_example_test.go @@ -20,11 +20,11 @@ func ExampleNew() { } dbConnPool := gpool.New(time.Hour, - func() (interface{}, error) { + func() (any, error) { dbConn := new(DBConn) return dbConn, nil }, - func(i interface{}) { + func(i any) { // sample : close db conn // i.(DBConn).Conn.Close() }) @@ -42,12 +42,12 @@ func ExamplePool_Put() { } dbConnPool := gpool.New(time.Hour, - func() (interface{}, error) { + func() (any, error) { dbConn := new(DBConn) dbConn.Limit = 10 return dbConn, nil }, - func(i interface{}) { + func(i any) { // sample : close db conn // i.(DBConn).Conn.Close() }) @@ -76,12 +76,12 @@ func ExamplePool_Clear() { } dbConnPool := gpool.New(time.Hour, - func() (interface{}, error) { + func() (any, error) { dbConn := new(DBConn) dbConn.Limit = 10 return dbConn, nil }, - func(i interface{}) { + func(i any) { i.(*DBConn).Limit = 0 // sample : close db conn // i.(DBConn).Conn.Close() @@ -106,12 +106,12 @@ func ExamplePool_Get() { } dbConnPool := gpool.New(time.Hour, - func() (interface{}, error) { + func() (any, error) { dbConn := new(DBConn) dbConn.Limit = 10 return dbConn, nil }, - func(i interface{}) { + func(i any) { // sample : close db conn // i.(DBConn).Conn.Close() }) @@ -132,12 +132,12 @@ func ExamplePool_Size() { } dbConnPool := gpool.New(time.Hour, - func() (interface{}, error) { + func() (any, error) { dbConn := new(DBConn) dbConn.Limit = 10 return dbConn, nil }, - func(i interface{}) { + func(i any) { // sample : close db conn // i.(DBConn).Conn.Close() }) @@ -159,12 +159,12 @@ func ExamplePool_Close() { Limit int } var ( - newFunc = func() (interface{}, error) { + newFunc = func() (any, error) { dbConn := new(DBConn) dbConn.Limit = 10 return dbConn, nil } - closeFunc = func(i interface{}) { + closeFunc = func(i any) { fmt.Println("Close The Pool") // sample : close db conn // i.(DBConn).Conn.Close() diff --git a/container/gpool/gpool_z_unit_test.go b/container/gpool/gpool_z_unit_test.go index 7becbec569a..9ffe94c9d43 100644 --- a/container/gpool/gpool_z_unit_test.go +++ b/container/gpool/gpool_z_unit_test.go @@ -17,13 +17,13 @@ import ( "github.com/gogf/gf/v2/test/gtest" ) -var nf gpool.NewFunc = func() (i interface{}, e error) { +var nf gpool.NewFunc = func() (i any, e error) { return "hello", nil } var assertIndex = gtype.NewInt(0) -var ef gpool.ExpireFunc = func(i interface{}) { +var ef gpool.ExpireFunc = func(i any) { assertIndex.Add(1) gtest.Assert(i, assertIndex) } @@ -100,7 +100,7 @@ func Test_Gpool(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - p := gpool.New(time.Millisecond*200, nil, func(i interface{}) {}) + p := gpool.New(time.Millisecond*200, nil, func(i any) {}) p.Put(1) time.Sleep(time.Millisecond * 100) p.Put(2) @@ -109,7 +109,7 @@ func Test_Gpool(t *testing.T) { gtest.C(t, func(t *gtest.T) { s := make([]int, 0) - p := gpool.New(time.Millisecond*200, nil, func(i interface{}) { + p := gpool.New(time.Millisecond*200, nil, func(i any) { s = append(s, i.(int)) }) for i := 0; i < 5; i++ { diff --git a/container/gqueue/gqueue.go b/container/gqueue/gqueue.go index 5923db1b43b..e20e0ec9418 100644 --- a/container/gqueue/gqueue.go +++ b/container/gqueue/gqueue.go @@ -26,11 +26,11 @@ import ( // Queue is a concurrent-safe queue built on doubly linked list and channel. type Queue struct { - limit int // Limit for queue size. - list *glist.List // Underlying list structure for data maintaining. - closed *gtype.Bool // Whether queue is closed. - events chan struct{} // Events for data writing. - C chan interface{} // Underlying channel for data reading. + limit int // Limit for queue size. + list *glist.List // Underlying list structure for data maintaining. + closed *gtype.Bool // Whether queue is closed. + events chan struct{} // Events for data writing. + C chan any // Underlying channel for data reading. } const ( @@ -47,11 +47,11 @@ func New(limit ...int) *Queue { } if len(limit) > 0 && limit[0] > 0 { q.limit = limit[0] - q.C = make(chan interface{}, limit[0]) + q.C = make(chan any, limit[0]) } else { q.list = glist.New(true) q.events = make(chan struct{}, math.MaxInt32) - q.C = make(chan interface{}, defaultQueueSize) + q.C = make(chan any, defaultQueueSize) go q.asyncLoopFromListToChannel() } return q @@ -59,7 +59,7 @@ func New(limit ...int) *Queue { // Push pushes the data `v` into the queue. // Note that it would panic if Push is called after the queue is closed. -func (q *Queue) Push(v interface{}) { +func (q *Queue) Push(v any) { if q.limit > 0 { q.C <- v } else { @@ -72,7 +72,7 @@ func (q *Queue) Push(v interface{}) { // Pop pops an item from the queue in FIFO way. // Note that it would return nil immediately if Pop is called after the queue is closed. -func (q *Queue) Pop() interface{} { +func (q *Queue) Pop() any { return <-q.C } diff --git a/container/gqueue/gqueue_z_bench_test.go b/container/gqueue/gqueue_z_bench_test.go index 897b54d05fe..53859b5ac93 100644 --- a/container/gqueue/gqueue_z_bench_test.go +++ b/container/gqueue/gqueue_z_bench_test.go @@ -22,7 +22,7 @@ var qstatic = gqueue.New(length) var qdynamic = gqueue.New() -var cany = make(chan interface{}, length) +var cany = make(chan any, length) func Benchmark_Gqueue_StaticPushAndPop(b *testing.B) { b.N = bn diff --git a/container/gring/gring.go b/container/gring/gring.go index 3700bd0446a..3a0893c61a6 100644 --- a/container/gring/gring.go +++ b/container/gring/gring.go @@ -29,7 +29,7 @@ type Ring struct { // internalRingItem stores the ring element value. type internalRingItem struct { - Value interface{} + Value any } // New creates and returns a Ring structure of `cap` elements. @@ -48,8 +48,8 @@ func New(cap int, safe ...bool) *Ring { } // Val returns the item's value of current position. -func (r *Ring) Val() interface{} { - var value interface{} +func (r *Ring) Val() any { + var value any r.mu.RLock() if r.ring.Value != nil { value = r.ring.Value.(internalRingItem).Value @@ -97,7 +97,7 @@ func (r *Ring) checkAndUpdateLenAndCap() { } // Set sets value to the item of current position. -func (r *Ring) Set(value interface{}) *Ring { +func (r *Ring) Set(value any) *Ring { r.mu.Lock() if r.ring.Value == nil { r.len.Add(1) @@ -108,7 +108,7 @@ func (r *Ring) Set(value interface{}) *Ring { } // Put sets `value` to current item of ring and moves position to next item. -func (r *Ring) Put(value interface{}) *Ring { +func (r *Ring) Put(value any) *Ring { r.mu.Lock() if r.ring.Value == nil { r.len.Add(1) @@ -187,7 +187,7 @@ func (r *Ring) Unlink(n int) *Ring { // RLockIteratorNext iterates and locks reading forward // with given callback function `f` within RWMutex.RLock. // If `f` returns true, then it continues iterating; or false to stop. -func (r *Ring) RLockIteratorNext(f func(value interface{}) bool) { +func (r *Ring) RLockIteratorNext(f func(value any) bool) { r.mu.RLock() defer r.mu.RUnlock() if r.ring.Value != nil && !f(r.ring.Value.(internalRingItem).Value) { @@ -203,7 +203,7 @@ func (r *Ring) RLockIteratorNext(f func(value interface{}) bool) { // RLockIteratorPrev iterates and locks writing backward // with given callback function `f` within RWMutex.RLock. // If `f` returns true, then it continues iterating; or false to stop. -func (r *Ring) RLockIteratorPrev(f func(value interface{}) bool) { +func (r *Ring) RLockIteratorPrev(f func(value any) bool) { r.mu.RLock() defer r.mu.RUnlock() if r.ring.Value != nil && !f(r.ring.Value.(internalRingItem).Value) { @@ -217,8 +217,8 @@ func (r *Ring) RLockIteratorPrev(f func(value interface{}) bool) { } // SliceNext returns a copy of all item values as slice forward from current position. -func (r *Ring) SliceNext() []interface{} { - s := make([]interface{}, 0) +func (r *Ring) SliceNext() []any { + s := make([]any, 0) r.mu.RLock() if r.ring.Value != nil { s = append(s, r.ring.Value.(internalRingItem).Value) @@ -234,8 +234,8 @@ func (r *Ring) SliceNext() []interface{} { } // SlicePrev returns a copy of all item values as slice backward from current position. -func (r *Ring) SlicePrev() []interface{} { - s := make([]interface{}, 0) +func (r *Ring) SlicePrev() []any { + s := make([]any, 0) r.mu.RLock() if r.ring.Value != nil { s = append(s, r.ring.Value.(internalRingItem).Value) diff --git a/container/gring/gring_z_example_test.go b/container/gring/gring_z_example_test.go index 0cf3d2ec817..5f3b5edd69f 100644 --- a/container/gring/gring_z_example_test.go +++ b/container/gring/gring_z_example_test.go @@ -222,7 +222,7 @@ func ExampleRing_RLockIteratorNext() { r.Set(i).Next() } - r.RLockIteratorNext(func(value interface{}) bool { + r.RLockIteratorNext(func(value any) bool { if value.(int) < 5 { fmt.Println("IteratorNext Success, Value:", value) return true @@ -248,7 +248,7 @@ func ExampleRing_RLockIteratorPrev() { // move r to pos 9 r.Prev() - r.RLockIteratorPrev(func(value interface{}) bool { + r.RLockIteratorPrev(func(value any) bool { if value.(int) >= 5 { fmt.Println("IteratorPrev Success, Value:", value) return true diff --git a/container/gring/gring_z_unit_test.go b/container/gring/gring_z_unit_test.go index 002bd5f94bd..4f3c847e9a7 100644 --- a/container/gring/gring_z_unit_test.go +++ b/container/gring/gring_z_unit_test.go @@ -193,7 +193,7 @@ func TestRing_RLockIteratorNext(t *testing.T) { } iterVal := 0 - r.RLockIteratorNext(func(value interface{}) bool { + r.RLockIteratorNext(func(value any) bool { if value.(int) == 0 { iterVal = value.(int) return false @@ -213,7 +213,7 @@ func TestRing_RLockIteratorPrev(t *testing.T) { } iterVal := 0 - r.RLockIteratorPrev(func(value interface{}) bool { + r.RLockIteratorPrev(func(value any) bool { if value.(int) == 0 { iterVal = value.(int) return false diff --git a/container/gset/gset_any_set.go b/container/gset/gset_any_set.go index 5bc58a27b9a..de816c652b3 100644 --- a/container/gset/gset_any_set.go +++ b/container/gset/gset_any_set.go @@ -16,10 +16,10 @@ import ( "github.com/gogf/gf/v2/util/gconv" ) -// Set is consisted of interface{} items. +// Set is consisted of any items. type Set struct { mu rwmutex.RWMutex - data map[interface{}]struct{} + data map[any]struct{} } // New create and returns a new set, which contains un-repeated items. @@ -33,15 +33,15 @@ func New(safe ...bool) *Set { // Also see New. func NewSet(safe ...bool) *Set { return &Set{ - data: make(map[interface{}]struct{}), + data: make(map[any]struct{}), mu: rwmutex.Create(safe...), } } // NewFrom returns a new set from `items`. // Parameter `items` can be either a variable of any type, or a slice. -func NewFrom(items interface{}, safe ...bool) *Set { - m := make(map[interface{}]struct{}) +func NewFrom(items any, safe ...bool) *Set { + m := make(map[any]struct{}) for _, v := range gconv.Interfaces(items) { m[v] = struct{}{} } @@ -53,7 +53,7 @@ func NewFrom(items interface{}, safe ...bool) *Set { // Iterator iterates the set readonly with given callback function `f`, // if `f` returns true then continue iterating; or false to stop. -func (set *Set) Iterator(f func(v interface{}) bool) { +func (set *Set) Iterator(f func(v any) bool) { for _, k := range set.Slice() { if !f(k) { break @@ -62,10 +62,10 @@ func (set *Set) Iterator(f func(v interface{}) bool) { } // Add adds one or multiple items to the set. -func (set *Set) Add(items ...interface{}) { +func (set *Set) Add(items ...any) { set.mu.Lock() if set.data == nil { - set.data = make(map[interface{}]struct{}) + set.data = make(map[any]struct{}) } for _, v := range items { set.data[v] = struct{}{} @@ -78,7 +78,7 @@ func (set *Set) Add(items ...interface{}) { // or else it does nothing and returns false. // // Note that, if `item` is nil, it does nothing and returns false. -func (set *Set) AddIfNotExist(item interface{}) bool { +func (set *Set) AddIfNotExist(item any) bool { if item == nil { return false } @@ -86,7 +86,7 @@ func (set *Set) AddIfNotExist(item interface{}) bool { set.mu.Lock() defer set.mu.Unlock() if set.data == nil { - set.data = make(map[interface{}]struct{}) + set.data = make(map[any]struct{}) } if _, ok := set.data[item]; !ok { set.data[item] = struct{}{} @@ -102,7 +102,7 @@ func (set *Set) AddIfNotExist(item interface{}) bool { // // Note that, if `item` is nil, it does nothing and returns false. The function `f` // is executed without writing lock. -func (set *Set) AddIfNotExistFunc(item interface{}, f func() bool) bool { +func (set *Set) AddIfNotExistFunc(item any, f func() bool) bool { if item == nil { return false } @@ -111,7 +111,7 @@ func (set *Set) AddIfNotExistFunc(item interface{}, f func() bool) bool { set.mu.Lock() defer set.mu.Unlock() if set.data == nil { - set.data = make(map[interface{}]struct{}) + set.data = make(map[any]struct{}) } if _, ok := set.data[item]; !ok { set.data[item] = struct{}{} @@ -128,7 +128,7 @@ func (set *Set) AddIfNotExistFunc(item interface{}, f func() bool) bool { // // Note that, if `item` is nil, it does nothing and returns false. The function `f` // is executed within writing lock. -func (set *Set) AddIfNotExistFuncLock(item interface{}, f func() bool) bool { +func (set *Set) AddIfNotExistFuncLock(item any, f func() bool) bool { if item == nil { return false } @@ -136,7 +136,7 @@ func (set *Set) AddIfNotExistFuncLock(item interface{}, f func() bool) bool { set.mu.Lock() defer set.mu.Unlock() if set.data == nil { - set.data = make(map[interface{}]struct{}) + set.data = make(map[any]struct{}) } if f() { if _, ok := set.data[item]; !ok { @@ -149,7 +149,7 @@ func (set *Set) AddIfNotExistFuncLock(item interface{}, f func() bool) bool { } // Contains checks whether the set contains `item`. -func (set *Set) Contains(item interface{}) bool { +func (set *Set) Contains(item any) bool { var ok bool set.mu.RLock() if set.data != nil { @@ -160,7 +160,7 @@ func (set *Set) Contains(item interface{}) bool { } // Remove deletes `item` from set. -func (set *Set) Remove(item interface{}) { +func (set *Set) Remove(item any) { set.mu.Lock() if set.data != nil { delete(set.data, item) @@ -179,16 +179,16 @@ func (set *Set) Size() int { // Clear deletes all items of the set. func (set *Set) Clear() { set.mu.Lock() - set.data = make(map[interface{}]struct{}) + set.data = make(map[any]struct{}) set.mu.Unlock() } // Slice returns all items of the set as slice. -func (set *Set) Slice() []interface{} { +func (set *Set) Slice() []any { set.mu.RLock() var ( i = 0 - ret = make([]interface{}, len(set.data)) + ret = make([]any, len(set.data)) ) for item := range set.data { ret[i] = item @@ -251,14 +251,14 @@ func (set *Set) String() string { } // LockFunc locks writing with callback function `f`. -func (set *Set) LockFunc(f func(m map[interface{}]struct{})) { +func (set *Set) LockFunc(f func(m map[any]struct{})) { set.mu.Lock() defer set.mu.Unlock() f(set.data) } // RLockFunc locks reading with callback function `f`. -func (set *Set) RLockFunc(f func(m map[interface{}]struct{})) { +func (set *Set) RLockFunc(f func(m map[any]struct{})) { set.mu.RLock() defer set.mu.RUnlock() f(set.data) @@ -422,7 +422,7 @@ func (set *Set) Sum() (sum int) { } // Pop randomly pops an item from set. -func (set *Set) Pop() interface{} { +func (set *Set) Pop() any { set.mu.Lock() defer set.mu.Unlock() for k := range set.data { @@ -434,7 +434,7 @@ func (set *Set) Pop() interface{} { // Pops randomly pops `size` items from set. // It returns all items if size == -1. -func (set *Set) Pops(size int) []interface{} { +func (set *Set) Pops(size int) []any { set.mu.Lock() defer set.mu.Unlock() if size > len(set.data) || size == -1 { @@ -444,7 +444,7 @@ func (set *Set) Pops(size int) []interface{} { return nil } index := 0 - array := make([]interface{}, size) + array := make([]any, size) for k := range set.data { delete(set.data, k) array[index] = k @@ -457,10 +457,10 @@ func (set *Set) Pops(size int) []interface{} { } // Walk applies a user supplied function `f` to every item of set. -func (set *Set) Walk(f func(item interface{}) interface{}) *Set { +func (set *Set) Walk(f func(item any) any) *Set { set.mu.Lock() defer set.mu.Unlock() - m := make(map[interface{}]struct{}, len(set.data)) + m := make(map[any]struct{}, len(set.data)) for k, v := range set.data { m[f(k)] = v } @@ -478,9 +478,9 @@ func (set *Set) UnmarshalJSON(b []byte) error { set.mu.Lock() defer set.mu.Unlock() if set.data == nil { - set.data = make(map[interface{}]struct{}) + set.data = make(map[any]struct{}) } - var array []interface{} + var array []any if err := json.UnmarshalUseNumber(b, &array); err != nil { return err } @@ -491,13 +491,13 @@ func (set *Set) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for set. -func (set *Set) UnmarshalValue(value interface{}) (err error) { +func (set *Set) UnmarshalValue(value any) (err error) { set.mu.Lock() defer set.mu.Unlock() if set.data == nil { - set.data = make(map[interface{}]struct{}) + set.data = make(map[any]struct{}) } - var array []interface{} + var array []any switch value.(type) { case string, []byte: err = json.UnmarshalUseNumber(gconv.Bytes(value), &array) @@ -511,13 +511,13 @@ func (set *Set) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (set *Set) DeepCopy() interface{} { +func (set *Set) DeepCopy() any { if set == nil { return nil } set.mu.RLock() defer set.mu.RUnlock() - data := make([]interface{}, 0) + data := make([]any, 0) for k := range set.data { data = append(data, k) } diff --git a/container/gset/gset_int_set.go b/container/gset/gset_int_set.go index 08d97986994..211c7d86d39 100644 --- a/container/gset/gset_int_set.go +++ b/container/gset/gset_int_set.go @@ -450,7 +450,7 @@ func (set *IntSet) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for set. -func (set *IntSet) UnmarshalValue(value interface{}) (err error) { +func (set *IntSet) UnmarshalValue(value any) (err error) { set.mu.Lock() defer set.mu.Unlock() if set.data == nil { @@ -470,7 +470,7 @@ func (set *IntSet) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (set *IntSet) DeepCopy() interface{} { +func (set *IntSet) DeepCopy() any { if set == nil { return nil } diff --git a/container/gset/gset_str_set.go b/container/gset/gset_str_set.go index 6b880a74ffd..660c85a9378 100644 --- a/container/gset/gset_str_set.go +++ b/container/gset/gset_str_set.go @@ -480,7 +480,7 @@ func (set *StrSet) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for set. -func (set *StrSet) UnmarshalValue(value interface{}) (err error) { +func (set *StrSet) UnmarshalValue(value any) (err error) { set.mu.Lock() defer set.mu.Unlock() if set.data == nil { @@ -500,7 +500,7 @@ func (set *StrSet) UnmarshalValue(value interface{}) (err error) { } // DeepCopy implements interface for deep copy of current type. -func (set *StrSet) DeepCopy() interface{} { +func (set *StrSet) DeepCopy() any { if set == nil { return nil } diff --git a/container/gset/gset_z_unit_any_test.go b/container/gset/gset_z_unit_any_test.go index 3fd89d70b38..39ab7fb8a2a 100644 --- a/container/gset/gset_z_unit_any_test.go +++ b/container/gset/gset_z_unit_any_test.go @@ -26,7 +26,7 @@ func TestSet_Var(t *testing.T) { gtest.C(t, func(t *gtest.T) { var s gset.Set s.Add(1, 1, 2) - s.Add([]interface{}{3, 4}...) + s.Add([]any{3, 4}...) t.Assert(s.Size(), 4) t.AssertIN(1, s.Slice()) t.AssertIN(2, s.Slice()) @@ -46,7 +46,7 @@ func TestSet_New(t *testing.T) { gtest.C(t, func(t *gtest.T) { s := gset.New() s.Add(1, 1, 2) - s.Add([]interface{}{3, 4}...) + s.Add([]any{3, 4}...) t.Assert(s.Size(), 4) t.AssertIN(1, s.Slice()) t.AssertIN(2, s.Slice()) @@ -66,7 +66,7 @@ func TestSet_Basic(t *testing.T) { gtest.C(t, func(t *gtest.T) { s := gset.NewSet() s.Add(1, 1, 2) - s.Add([]interface{}{3, 4}...) + s.Add([]any{3, 4}...) t.Assert(s.Size(), 4) t.AssertIN(1, s.Slice()) t.AssertIN(2, s.Slice()) @@ -84,8 +84,8 @@ func TestSet_Basic(t *testing.T) { func TestSet_Iterator_Deadlock(t *testing.T) { gtest.C(t, func(t *gtest.T) { - set := gset.NewFrom([]interface{}{1, 2, 3, 4, 5}, true) - set.Iterator(func(k interface{}) bool { + set := gset.NewFrom([]any{1, 2, 3, 4, 5}, true) + set.Iterator(func(k any) bool { if gconv.Int(k)%2 == 0 { set.Remove(k) } @@ -107,11 +107,11 @@ func TestSet_Iterator(t *testing.T) { a1 := garray.New(true) a2 := garray.New(true) - s.Iterator(func(v interface{}) bool { + s.Iterator(func(v any) bool { a1.Append(1) return false }) - s.Iterator(func(v interface{}) bool { + s.Iterator(func(v any) bool { a2.Append(1) return true }) @@ -125,12 +125,12 @@ func TestSet_LockFunc(t *testing.T) { s := gset.NewSet() s.Add(1, 2, 3) t.Assert(s.Size(), 3) - s.LockFunc(func(m map[interface{}]struct{}) { + s.LockFunc(func(m map[any]struct{}) { delete(m, 1) }) t.Assert(s.Size(), 2) - s.RLockFunc(func(m map[interface{}]struct{}) { - t.Assert(m, map[interface{}]struct{}{ + s.RLockFunc(func(m map[any]struct{}) { + t.Assert(m, map[any]struct{}{ 3: {}, 2: {}, }) @@ -352,7 +352,7 @@ func TestSet_Pops(t *testing.T) { gtest.C(t, func(t *gtest.T) { s := gset.New(true) - a := []interface{}{1, 2, 3, 4} + a := []any{1, 2, 3, 4} s.Add(a...) t.Assert(s.Size(), 4) t.Assert(s.Pops(-2), nil) @@ -362,7 +362,7 @@ func TestSet_Pops(t *testing.T) { func TestSet_Json(t *testing.T) { gtest.C(t, func(t *gtest.T) { - s1 := []interface{}{"a", "b", "d", "c"} + s1 := []any{"a", "b", "d", "c"} a1 := gset.NewFrom(s1) b1, err1 := json.Marshal(a1) b2, err2 := json.Marshal(s1) @@ -442,7 +442,7 @@ func TestSet_Walk(t *testing.T) { gtest.C(t, func(t *gtest.T) { var set gset.Set set.Add(g.Slice{1, 2}...) - set.Walk(func(item interface{}) interface{} { + set.Walk(func(item any) any { return gconv.Int(item) + 10 }) t.Assert(set.Size(), 2) diff --git a/container/gtree/gtree.go b/container/gtree/gtree.go index 185c7c0206c..461756c2b66 100644 --- a/container/gtree/gtree.go +++ b/container/gtree/gtree.go @@ -14,77 +14,77 @@ import "github.com/gogf/gf/v2/container/gvar" // iTree defines the interface for basic operations of a tree. type iTree interface { // Set sets key-value pair into the tree. - Set(key interface{}, value interface{}) + Set(key any, value any) // Sets batch sets key-values to the tree. - Sets(data map[interface{}]interface{}) + Sets(data map[any]any) // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true. // It returns false if `key` exists, and such setting key-value pair operation would be ignored. - SetIfNotExist(key interface{}, value interface{}) bool + SetIfNotExist(key any, value any) bool // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true. // It returns false if `key` exists, and such setting key-value pair operation would be ignored. - SetIfNotExistFunc(key interface{}, f func() interface{}) bool + SetIfNotExistFunc(key any, f func() any) bool // SetIfNotExistFuncLock sets value with return value of callback function `f`, and then returns true. // It returns false if `key` exists, and such setting key-value pair operation would be ignored. // // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that // it executes function `f` within mutex.Lock of the hash map. - SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool + SetIfNotExistFuncLock(key any, f func() any) bool // Get searches the `key` in the tree and returns its associated `value` or nil if key is not found in tree. // // Note that, the `nil` value from Get function cannot be used to determine key existence, please use Contains // function to do so. - Get(key interface{}) (value interface{}) + Get(key any) (value any) // GetOrSet returns its `value` of `key`, or sets value with given `value` if it does not exist and then returns // this value. - GetOrSet(key interface{}, value interface{}) interface{} + GetOrSet(key any, value any) any // GetOrSetFunc returns its `value` of `key`, or sets value with returned value of callback function `f` if it does // not exist and then returns this value. - GetOrSetFunc(key interface{}, f func() interface{}) interface{} + GetOrSetFunc(key any, f func() any) any // GetOrSetFuncLock returns its `value` of `key`, or sets value with returned value of callback function `f` if it // does not exist and then returns this value. // // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` within mutex.Lock of the // hash map. - GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} + GetOrSetFuncLock(key any, f func() any) any // GetVar returns a gvar.Var with the value by given `key`. // Note that, the returned gvar.Var is un-concurrent safe. // // Also see function Get. - GetVar(key interface{}) *gvar.Var + GetVar(key any) *gvar.Var // GetVarOrSet returns a gvar.Var with result from GetVarOrSet. // Note that, the returned gvar.Var is un-concurrent safe. // // Also see function GetOrSet. - GetVarOrSet(key interface{}, value interface{}) *gvar.Var + GetVarOrSet(key any, value any) *gvar.Var // GetVarOrSetFunc returns a gvar.Var with result from GetOrSetFunc. // Note that, the returned gvar.Var is un-concurrent safe. // // Also see function GetOrSetFunc. - GetVarOrSetFunc(key interface{}, f func() interface{}) *gvar.Var + GetVarOrSetFunc(key any, f func() any) *gvar.Var // GetVarOrSetFuncLock returns a gvar.Var with result from GetOrSetFuncLock. // Note that, the returned gvar.Var is un-concurrent safe. // // Also see function GetOrSetFuncLock. - GetVarOrSetFuncLock(key interface{}, f func() interface{}) *gvar.Var + GetVarOrSetFuncLock(key any, f func() any) *gvar.Var // Search searches the tree with given `key`. // Second return parameter `found` is true if key was found, otherwise false. - Search(key interface{}) (value interface{}, found bool) + Search(key any) (value any, found bool) // Contains checks and returns whether given `key` exists in the tree. - Contains(key interface{}) bool + Contains(key any) bool // Size returns number of nodes in the tree. Size() int @@ -94,22 +94,22 @@ type iTree interface { // Remove removes the node from the tree by `key`, and returns its associated value of `key`. // The given `key` should adhere to the comparator's type assertion, otherwise method panics. - Remove(key interface{}) (value interface{}) + Remove(key any) (value any) // Removes batch deletes key-value pairs from the tree by `keys`. - Removes(keys []interface{}) + Removes(keys []any) // Clear removes all nodes from the tree. Clear() // Keys returns all keys from the tree in order by its comparator. - Keys() []interface{} + Keys() []any // Values returns all values from the true in order by its comparator based on the key. - Values() []interface{} + Values() []any // Replace clears the data of the tree and sets the nodes by given `data`. - Replace(data map[interface{}]interface{}) + Replace(data map[any]any) // Print prints the tree to stdout. Print() @@ -121,24 +121,24 @@ type iTree interface { MarshalJSON() (jsonBytes []byte, err error) // Map returns all key-value pairs as map. - Map() map[interface{}]interface{} + Map() map[any]any // MapStrAny returns all key-value items as map[string]any. - MapStrAny() map[string]interface{} + MapStrAny() map[string]any // Iterator is alias of IteratorAsc. // // Also see IteratorAsc. - Iterator(f func(key, value interface{}) bool) + Iterator(f func(key, value any) bool) // IteratorFrom is alias of IteratorAscFrom. // // Also see IteratorAscFrom. - IteratorFrom(key interface{}, match bool, f func(key, value interface{}) bool) + IteratorFrom(key any, match bool, f func(key, value any) bool) // IteratorAsc iterates the tree readonly in ascending order with given callback function `f`. // If callback function `f` returns true, then it continues iterating; or false to stop. - IteratorAsc(f func(key, value interface{}) bool) + IteratorAsc(f func(key, value any) bool) // IteratorAscFrom iterates the tree readonly in ascending order with given callback function `f`. // @@ -146,12 +146,12 @@ type iTree interface { // The parameter `match` specifies whether starting iterating only if the `key` is fully matched, or else using // index searching iterating. // If callback function `f` returns true, then it continues iterating; or false to stop. - IteratorAscFrom(key interface{}, match bool, f func(key, value interface{}) bool) + IteratorAscFrom(key any, match bool, f func(key, value any) bool) // IteratorDesc iterates the tree readonly in descending order with given callback function `f`. // // If callback function `f` returns true, then it continues iterating; or false to stop. - IteratorDesc(f func(key, value interface{}) bool) + IteratorDesc(f func(key, value any) bool) // IteratorDescFrom iterates the tree readonly in descending order with given callback function `f`. // @@ -159,7 +159,7 @@ type iTree interface { // The parameter `match` specifies whether starting iterating only if the `key` is fully matched, or else using // index searching iterating. // If callback function `f` returns true, then it continues iterating; or false to stop. - IteratorDescFrom(key interface{}, match bool, f func(key, value interface{}) bool) + IteratorDescFrom(key any, match bool, f func(key, value any) bool) } // iteratorFromGetIndex returns the index of the key in the keys slice. diff --git a/container/gtree/gtree_z_avl_tree_test.go b/container/gtree/gtree_z_avl_tree_test.go index c46afa899ce..ffc711ebd92 100644 --- a/container/gtree/gtree_z_avl_tree_test.go +++ b/container/gtree/gtree_z_avl_tree_test.go @@ -20,7 +20,7 @@ func Test_AVLTree_Basic(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gtree.NewAVLTree(gutil.ComparatorString) m.Set("key1", "val1") - t.Assert(m.Keys(), []interface{}{"key1"}) + t.Assert(m.Keys(), []any{"key1"}) t.Assert(m.Get("key1"), "val1") t.Assert(m.Size(), 1) @@ -40,20 +40,20 @@ func Test_AVLTree_Basic(t *testing.T) { t.AssertIN("val3", m.Values()) t.AssertIN("val1", m.Values()) - m.Sets(map[interface{}]interface{}{"key3": "val3", "key1": "val1"}) + m.Sets(map[any]any{"key3": "val3", "key1": "val1"}) m.Flip() - t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) + t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"}) m.Flip(gutil.ComparatorString) - t.Assert(m.Map(), map[interface{}]interface{}{"key3": "val3", "key1": "val1"}) + t.Assert(m.Map(), map[any]any{"key3": "val3", "key1": "val1"}) m.Clear() t.Assert(m.Size(), 0) t.Assert(m.IsEmpty(), true) - m2 := gtree.NewAVLTreeFrom(gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) - t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, "key1": "val1"}) + m2 := gtree.NewAVLTreeFrom(gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"}) + t.Assert(m2.Map(), map[any]any{1: 1, "key1": "val1"}) }) } @@ -102,10 +102,10 @@ func Test_AVLTree_Get_Set_Var(t *testing.T) { func Test_AVLTree_Batch(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gtree.NewAVLTree(gutil.ComparatorString) - m.Sets(map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - t.Assert(m.Map(), map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - m.Removes([]interface{}{"key1", 1}) - t.Assert(m.Map(), map[interface{}]interface{}{"key2": "val2", "key3": "val3"}) + m.Sets(map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + t.Assert(m.Map(), map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + m.Removes([]any{"key1", 1}) + t.Assert(m.Map(), map[any]any{"key2": "val2", "key3": "val3"}) }) } @@ -115,19 +115,19 @@ func Test_AVLTree_Iterator(t *testing.T) { keyLen := len(keys) index := 0 - expect := map[interface{}]interface{}{"key4": "val4", 1: 1, "key1": "val1", "key2": "val2", "key3": "val3"} + expect := map[any]any{"key4": "val4", 1: 1, "key1": "val1", "key2": "val2", "key3": "val3"} m := gtree.NewAVLTreeFrom(gutil.ComparatorString, expect) gtest.C(t, func(t *gtest.T) { - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { t.Assert(k, keys[index]) index++ t.Assert(expect[k], v) return true }) - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { index-- t.Assert(k, keys[index]) t.Assert(expect[k], v) @@ -140,11 +140,11 @@ func Test_AVLTree_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { i := 0 j := 0 - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { i++ return true }) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { j++ return false }) @@ -155,11 +155,11 @@ func Test_AVLTree_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { i := 0 j := 0 - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { i++ return true }) - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { j++ return false }) @@ -170,7 +170,7 @@ func Test_AVLTree_Iterator(t *testing.T) { } func Test_AVLTree_IteratorFrom(t *testing.T) { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 10; i++ { m[i] = i * 10 } @@ -178,7 +178,7 @@ func Test_AVLTree_IteratorFrom(t *testing.T) { gtest.C(t, func(t *gtest.T) { n := 5 - tree.IteratorFrom(5, true, func(key, value interface{}) bool { + tree.IteratorFrom(5, true, func(key, value any) bool { t.Assert(n, key) t.Assert(n*10, value) n++ @@ -186,7 +186,7 @@ func Test_AVLTree_IteratorFrom(t *testing.T) { }) i := 5 - tree.IteratorAscFrom(5, true, func(key, value interface{}) bool { + tree.IteratorAscFrom(5, true, func(key, value any) bool { t.Assert(i, key) t.Assert(i*10, value) i++ @@ -194,7 +194,7 @@ func Test_AVLTree_IteratorFrom(t *testing.T) { }) j := 5 - tree.IteratorDescFrom(5, true, func(key, value interface{}) bool { + tree.IteratorDescFrom(5, true, func(key, value any) bool { t.Assert(j, key) t.Assert(j*10, value) j-- @@ -206,7 +206,7 @@ func Test_AVLTree_IteratorFrom(t *testing.T) { func Test_AVLTree_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { //clone 方法是深克隆 - m := gtree.NewAVLTreeFrom(gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) + m := gtree.NewAVLTreeFrom(gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"}) m_clone := m.Clone() m.Remove(1) //修改原 map,clone 后的 map 不影响 @@ -219,7 +219,7 @@ func Test_AVLTree_Clone(t *testing.T) { } func Test_AVLTree_LRNode(t *testing.T) { - expect := map[interface{}]interface{}{"key4": "val4", "key1": "val1", "key2": "val2", "key3": "val3"} + expect := map[any]any{"key4": "val4", "key1": "val1", "key2": "val2", "key3": "val3"} //safe gtest.C(t, func(t *gtest.T) { m := gtree.NewAVLTreeFrom(gutil.ComparatorString, expect) @@ -235,7 +235,7 @@ func Test_AVLTree_LRNode(t *testing.T) { } func Test_AVLTree_CeilingFloor(t *testing.T) { - expect := map[interface{}]interface{}{ + expect := map[any]any{ 20: "val20", 6: "val6", 10: "val10", diff --git a/container/gtree/gtree_z_b_tree_test.go b/container/gtree/gtree_z_b_tree_test.go index 3462d006090..9dee970e4e9 100644 --- a/container/gtree/gtree_z_b_tree_test.go +++ b/container/gtree/gtree_z_b_tree_test.go @@ -23,7 +23,7 @@ func Test_BTree_Basic(t *testing.T) { t.Assert(m.Height(), 1) - t.Assert(m.Keys(), []interface{}{"key1"}) + t.Assert(m.Keys(), []any{"key1"}) t.Assert(m.Get("key1"), "val1") t.Assert(m.Size(), 1) @@ -46,8 +46,8 @@ func Test_BTree_Basic(t *testing.T) { t.Assert(m.Size(), 0) t.Assert(m.IsEmpty(), true) - m2 := gtree.NewBTreeFrom(3, gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) - t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, "key1": "val1"}) + m2 := gtree.NewBTreeFrom(3, gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"}) + t.Assert(m2.Map(), map[any]any{1: 1, "key1": "val1"}) }) } @@ -96,10 +96,10 @@ func Test_BTree_Get_Set_Var(t *testing.T) { func Test_BTree_Batch(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gtree.NewBTree(3, gutil.ComparatorString) - m.Sets(map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - t.Assert(m.Map(), map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - m.Removes([]interface{}{"key1", 1}) - t.Assert(m.Map(), map[interface{}]interface{}{"key2": "val2", "key3": "val3"}) + m.Sets(map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + t.Assert(m.Map(), map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + m.Removes([]any{"key1", 1}) + t.Assert(m.Map(), map[any]any{"key2": "val2", "key3": "val3"}) }) } @@ -108,19 +108,19 @@ func Test_BTree_Iterator(t *testing.T) { keyLen := len(keys) index := 0 - expect := map[interface{}]interface{}{"key4": "val4", 1: 1, "key1": "val1", "key2": "val2", "key3": "val3"} + expect := map[any]any{"key4": "val4", 1: 1, "key1": "val1", "key2": "val2", "key3": "val3"} m := gtree.NewBTreeFrom(3, gutil.ComparatorString, expect) gtest.C(t, func(t *gtest.T) { - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { t.Assert(k, keys[index]) index++ t.Assert(expect[k], v) return true }) - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { index-- t.Assert(k, keys[index]) t.Assert(expect[k], v) @@ -133,11 +133,11 @@ func Test_BTree_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { i := 0 j := 0 - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { i++ return true }) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { j++ return false }) @@ -148,11 +148,11 @@ func Test_BTree_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { i := 0 j := 0 - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { i++ return true }) - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { j++ return false }) @@ -162,7 +162,7 @@ func Test_BTree_Iterator(t *testing.T) { } func Test_BTree_IteratorFrom(t *testing.T) { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 10; i++ { m[i] = i * 10 } @@ -170,7 +170,7 @@ func Test_BTree_IteratorFrom(t *testing.T) { gtest.C(t, func(t *gtest.T) { n := 5 - tree.IteratorFrom(5, true, func(key, value interface{}) bool { + tree.IteratorFrom(5, true, func(key, value any) bool { t.Assert(n, key) t.Assert(n*10, value) n++ @@ -178,7 +178,7 @@ func Test_BTree_IteratorFrom(t *testing.T) { }) i := 5 - tree.IteratorAscFrom(5, true, func(key, value interface{}) bool { + tree.IteratorAscFrom(5, true, func(key, value any) bool { t.Assert(i, key) t.Assert(i*10, value) i++ @@ -186,7 +186,7 @@ func Test_BTree_IteratorFrom(t *testing.T) { }) j := 5 - tree.IteratorDescFrom(5, true, func(key, value interface{}) bool { + tree.IteratorDescFrom(5, true, func(key, value any) bool { t.Assert(j, key) t.Assert(j*10, value) j-- @@ -198,7 +198,7 @@ func Test_BTree_IteratorFrom(t *testing.T) { func Test_BTree_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { //clone 方法是深克隆 - m := gtree.NewBTreeFrom(3, gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) + m := gtree.NewBTreeFrom(3, gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"}) m_clone := m.Clone() m.Remove(1) //修改原 map,clone 后的 map 不影响 @@ -211,7 +211,7 @@ func Test_BTree_Clone(t *testing.T) { } func Test_BTree_LRNode(t *testing.T) { - expect := map[interface{}]interface{}{"key4": "val4", "key1": "val1", "key2": "val2", "key3": "val3"} + expect := map[any]any{"key4": "val4", "key1": "val1", "key2": "val2", "key3": "val3"} //safe gtest.C(t, func(t *gtest.T) { m := gtree.NewBTreeFrom(3, gutil.ComparatorString, expect) diff --git a/container/gtree/gtree_z_example_avltree_test.go b/container/gtree/gtree_z_example_avltree_test.go index edb73300beb..5dd24229e9f 100644 --- a/container/gtree/gtree_z_example_avltree_test.go +++ b/container/gtree/gtree_z_example_avltree_test.go @@ -48,7 +48,7 @@ func ExampleAVLTree_Set() { func ExampleAVLTree_Sets() { tree := gtree.NewAVLTree(gutil.ComparatorString) - tree.Sets(map[interface{}]interface{}{ + tree.Sets(map[any]any{ "key1": "val1", "key2": "val2", }) @@ -95,10 +95,10 @@ func ExampleAVLTree_GetOrSetFunc() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetOrSetFunc("key1", func() interface{} { + fmt.Println(tree.GetOrSetFunc("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetOrSetFunc("key6", func() interface{} { + fmt.Println(tree.GetOrSetFunc("key6", func() any { return "val6" })) @@ -113,10 +113,10 @@ func ExampleAVLTree_GetOrSetFuncLock() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetOrSetFuncLock("key1", func() interface{} { + fmt.Println(tree.GetOrSetFuncLock("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetOrSetFuncLock("key6", func() interface{} { + fmt.Println(tree.GetOrSetFuncLock("key6", func() any { return "val6" })) @@ -157,10 +157,10 @@ func ExampleAVLTree_GetVarOrSetFunc() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetVarOrSetFunc("key1", func() interface{} { + fmt.Println(tree.GetVarOrSetFunc("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetVarOrSetFunc("key6", func() interface{} { + fmt.Println(tree.GetVarOrSetFunc("key6", func() any { return "val6" })) @@ -175,10 +175,10 @@ func ExampleAVLTree_GetVarOrSetFuncLock() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetVarOrSetFuncLock("key1", func() interface{} { + fmt.Println(tree.GetVarOrSetFuncLock("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetVarOrSetFuncLock("key6", func() interface{} { + fmt.Println(tree.GetVarOrSetFuncLock("key6", func() any { return "val6" })) @@ -207,10 +207,10 @@ func ExampleAVLTree_SetIfNotExistFunc() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.SetIfNotExistFunc("key1", func() interface{} { + fmt.Println(tree.SetIfNotExistFunc("key1", func() any { return "newVal1" })) - fmt.Println(tree.SetIfNotExistFunc("key6", func() interface{} { + fmt.Println(tree.SetIfNotExistFunc("key6", func() any { return "val6" })) @@ -225,10 +225,10 @@ func ExampleAVLTree_SetIfNotExistFuncLock() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.SetIfNotExistFuncLock("key1", func() interface{} { + fmt.Println(tree.SetIfNotExistFuncLock("key1", func() any { return "newVal1" })) - fmt.Println(tree.SetIfNotExistFuncLock("key6", func() interface{} { + fmt.Println(tree.SetIfNotExistFuncLock("key6", func() any { return "val6" })) @@ -273,7 +273,7 @@ func ExampleAVLTree_Removes() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - removeKeys := make([]interface{}, 2) + removeKeys := make([]any, 2) removeKeys = append(removeKeys, "key1") removeKeys = append(removeKeys, "key6") @@ -405,7 +405,7 @@ func ExampleAVLTree_Replace() { fmt.Println(tree.Map()) - data := map[interface{}]interface{}{ + data := map[any]any{ "newKey0": "newVal0", "newKey1": "newVal1", "newKey2": "newVal2", @@ -573,7 +573,7 @@ func ExampleAVLTree_Iterator() { } var totalKey, totalValue int - tree.Iterator(func(key, value interface{}) bool { + tree.Iterator(func(key, value any) bool { totalKey += key.(int) totalValue += value.(int) @@ -589,13 +589,13 @@ func ExampleAVLTree_Iterator() { } func ExampleAVLTree_IteratorFrom() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewAVLTreeFrom(gutil.ComparatorInt, m) - tree.IteratorFrom(1, true, func(key, value interface{}) bool { + tree.IteratorFrom(1, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -614,7 +614,7 @@ func ExampleAVLTree_IteratorAsc() { tree.Set(i, 10-i) } - tree.IteratorAsc(func(key, value interface{}) bool { + tree.IteratorAsc(func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -633,13 +633,13 @@ func ExampleAVLTree_IteratorAsc() { } func ExampleAVLTree_IteratorAscFrom_normal() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewAVLTreeFrom(gutil.ComparatorInt, m) - tree.IteratorAscFrom(1, true, func(key, value interface{}) bool { + tree.IteratorAscFrom(1, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -653,13 +653,13 @@ func ExampleAVLTree_IteratorAscFrom_normal() { } func ExampleAVLTree_IteratorAscFrom_noExistKey() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewAVLTreeFrom(gutil.ComparatorInt, m) - tree.IteratorAscFrom(0, true, func(key, value interface{}) bool { + tree.IteratorAscFrom(0, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -668,13 +668,13 @@ func ExampleAVLTree_IteratorAscFrom_noExistKey() { } func ExampleAVLTree_IteratorAscFrom_noExistKeyAndMatchFalse() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewAVLTreeFrom(gutil.ComparatorInt, m) - tree.IteratorAscFrom(6, false, func(key, value interface{}) bool { + tree.IteratorAscFrom(6, false, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -688,7 +688,7 @@ func ExampleAVLTree_IteratorDesc() { tree.Set(i, 10-i) } - tree.IteratorDesc(func(key, value interface{}) bool { + tree.IteratorDesc(func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -707,13 +707,13 @@ func ExampleAVLTree_IteratorDesc() { } func ExampleAVLTree_IteratorDescFrom() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewAVLTreeFrom(gutil.ComparatorInt, m) - tree.IteratorDescFrom(5, true, func(key, value interface{}) bool { + tree.IteratorDescFrom(5, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) diff --git a/container/gtree/gtree_z_example_btree_test.go b/container/gtree/gtree_z_example_btree_test.go index 718aa293b12..661311b31e1 100644 --- a/container/gtree/gtree_z_example_btree_test.go +++ b/container/gtree/gtree_z_example_btree_test.go @@ -48,7 +48,7 @@ func ExampleBTree_Set() { func ExampleBTree_Sets() { tree := gtree.NewBTree(3, gutil.ComparatorString) - tree.Sets(map[interface{}]interface{}{ + tree.Sets(map[any]any{ "key1": "val1", "key2": "val2", }) @@ -95,10 +95,10 @@ func ExampleBTree_GetOrSetFunc() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetOrSetFunc("key1", func() interface{} { + fmt.Println(tree.GetOrSetFunc("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetOrSetFunc("key6", func() interface{} { + fmt.Println(tree.GetOrSetFunc("key6", func() any { return "val6" })) @@ -113,10 +113,10 @@ func ExampleBTree_GetOrSetFuncLock() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetOrSetFuncLock("key1", func() interface{} { + fmt.Println(tree.GetOrSetFuncLock("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetOrSetFuncLock("key6", func() interface{} { + fmt.Println(tree.GetOrSetFuncLock("key6", func() any { return "val6" })) @@ -157,10 +157,10 @@ func ExampleBTree_GetVarOrSetFunc() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetVarOrSetFunc("key1", func() interface{} { + fmt.Println(tree.GetVarOrSetFunc("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetVarOrSetFunc("key6", func() interface{} { + fmt.Println(tree.GetVarOrSetFunc("key6", func() any { return "val6" })) @@ -175,10 +175,10 @@ func ExampleBTree_GetVarOrSetFuncLock() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetVarOrSetFuncLock("key1", func() interface{} { + fmt.Println(tree.GetVarOrSetFuncLock("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetVarOrSetFuncLock("key6", func() interface{} { + fmt.Println(tree.GetVarOrSetFuncLock("key6", func() any { return "val6" })) @@ -207,10 +207,10 @@ func ExampleBTree_SetIfNotExistFunc() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.SetIfNotExistFunc("key1", func() interface{} { + fmt.Println(tree.SetIfNotExistFunc("key1", func() any { return "newVal1" })) - fmt.Println(tree.SetIfNotExistFunc("key6", func() interface{} { + fmt.Println(tree.SetIfNotExistFunc("key6", func() any { return "val6" })) @@ -225,10 +225,10 @@ func ExampleBTree_SetIfNotExistFuncLock() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.SetIfNotExistFuncLock("key1", func() interface{} { + fmt.Println(tree.SetIfNotExistFuncLock("key1", func() any { return "newVal1" })) - fmt.Println(tree.SetIfNotExistFuncLock("key6", func() interface{} { + fmt.Println(tree.SetIfNotExistFuncLock("key6", func() any { return "val6" })) @@ -273,7 +273,7 @@ func ExampleBTree_Removes() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - removeKeys := make([]interface{}, 2) + removeKeys := make([]any, 2) removeKeys = append(removeKeys, "key1") removeKeys = append(removeKeys, "key6") @@ -388,7 +388,7 @@ func ExampleBTree_Replace() { fmt.Println(tree.Map()) - data := map[interface{}]interface{}{ + data := map[any]any{ "newKey0": "newVal0", "newKey1": "newVal1", "newKey2": "newVal2", @@ -499,7 +499,7 @@ func ExampleBTree_Iterator() { } var totalKey, totalValue int - tree.Iterator(func(key, value interface{}) bool { + tree.Iterator(func(key, value any) bool { totalKey += key.(int) totalValue += value.(int) @@ -515,13 +515,13 @@ func ExampleBTree_Iterator() { } func ExampleBTree_IteratorFrom() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewBTreeFrom(3, gutil.ComparatorInt, m) - tree.IteratorFrom(1, true, func(key, value interface{}) bool { + tree.IteratorFrom(1, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -540,7 +540,7 @@ func ExampleBTree_IteratorAsc() { tree.Set(i, 10-i) } - tree.IteratorAsc(func(key, value interface{}) bool { + tree.IteratorAsc(func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -559,13 +559,13 @@ func ExampleBTree_IteratorAsc() { } func ExampleBTree_IteratorAscFrom_normal() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewBTreeFrom(3, gutil.ComparatorInt, m) - tree.IteratorAscFrom(1, true, func(key, value interface{}) bool { + tree.IteratorAscFrom(1, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -579,13 +579,13 @@ func ExampleBTree_IteratorAscFrom_normal() { } func ExampleBTree_IteratorAscFrom_noExistKey() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewBTreeFrom(3, gutil.ComparatorInt, m) - tree.IteratorAscFrom(0, true, func(key, value interface{}) bool { + tree.IteratorAscFrom(0, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -594,13 +594,13 @@ func ExampleBTree_IteratorAscFrom_noExistKey() { } func ExampleBTree_IteratorAscFrom_noExistKeyAndMatchFalse() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewBTreeFrom(3, gutil.ComparatorInt, m) - tree.IteratorAscFrom(0, false, func(key, value interface{}) bool { + tree.IteratorAscFrom(0, false, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -619,7 +619,7 @@ func ExampleBTree_IteratorDesc() { tree.Set(i, 10-i) } - tree.IteratorDesc(func(key, value interface{}) bool { + tree.IteratorDesc(func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -638,13 +638,13 @@ func ExampleBTree_IteratorDesc() { } func ExampleBTree_IteratorDescFrom() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewBTreeFrom(3, gutil.ComparatorInt, m) - tree.IteratorDescFrom(5, true, func(key, value interface{}) bool { + tree.IteratorDescFrom(5, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) diff --git a/container/gtree/gtree_z_example_redblacktree_test.go b/container/gtree/gtree_z_example_redblacktree_test.go index 9ad50b4eee6..84d43477694 100644 --- a/container/gtree/gtree_z_example_redblacktree_test.go +++ b/container/gtree/gtree_z_example_redblacktree_test.go @@ -63,7 +63,7 @@ func ExampleRedBlackTree_Set() { func ExampleRedBlackTree_Sets() { tree := gtree.NewRedBlackTree(gutil.ComparatorString) - tree.Sets(map[interface{}]interface{}{ + tree.Sets(map[any]any{ "key1": "val1", "key2": "val2", }) @@ -110,10 +110,10 @@ func ExampleRedBlackTree_GetOrSetFunc() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetOrSetFunc("key1", func() interface{} { + fmt.Println(tree.GetOrSetFunc("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetOrSetFunc("key6", func() interface{} { + fmt.Println(tree.GetOrSetFunc("key6", func() any { return "val6" })) @@ -128,10 +128,10 @@ func ExampleRedBlackTree_GetOrSetFuncLock() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetOrSetFuncLock("key1", func() interface{} { + fmt.Println(tree.GetOrSetFuncLock("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetOrSetFuncLock("key6", func() interface{} { + fmt.Println(tree.GetOrSetFuncLock("key6", func() any { return "val6" })) @@ -172,10 +172,10 @@ func ExampleRedBlackTree_GetVarOrSetFunc() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetVarOrSetFunc("key1", func() interface{} { + fmt.Println(tree.GetVarOrSetFunc("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetVarOrSetFunc("key6", func() interface{} { + fmt.Println(tree.GetVarOrSetFunc("key6", func() any { return "val6" })) @@ -190,10 +190,10 @@ func ExampleRedBlackTree_GetVarOrSetFuncLock() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.GetVarOrSetFuncLock("key1", func() interface{} { + fmt.Println(tree.GetVarOrSetFuncLock("key1", func() any { return "newVal1" })) - fmt.Println(tree.GetVarOrSetFuncLock("key6", func() interface{} { + fmt.Println(tree.GetVarOrSetFuncLock("key6", func() any { return "val6" })) @@ -222,10 +222,10 @@ func ExampleRedBlackTree_SetIfNotExistFunc() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.SetIfNotExistFunc("key1", func() interface{} { + fmt.Println(tree.SetIfNotExistFunc("key1", func() any { return "newVal1" })) - fmt.Println(tree.SetIfNotExistFunc("key6", func() interface{} { + fmt.Println(tree.SetIfNotExistFunc("key6", func() any { return "val6" })) @@ -240,10 +240,10 @@ func ExampleRedBlackTree_SetIfNotExistFuncLock() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - fmt.Println(tree.SetIfNotExistFuncLock("key1", func() interface{} { + fmt.Println(tree.SetIfNotExistFuncLock("key1", func() any { return "newVal1" })) - fmt.Println(tree.SetIfNotExistFuncLock("key6", func() interface{} { + fmt.Println(tree.SetIfNotExistFuncLock("key6", func() any { return "val6" })) @@ -288,7 +288,7 @@ func ExampleRedBlackTree_Removes() { tree.Set("key"+gconv.String(i), "val"+gconv.String(i)) } - removeKeys := make([]interface{}, 2) + removeKeys := make([]any, 2) removeKeys = append(removeKeys, "key1") removeKeys = append(removeKeys, "key6") @@ -485,7 +485,7 @@ func ExampleRedBlackTree_Iterator() { } var totalKey, totalValue int - tree.Iterator(func(key, value interface{}) bool { + tree.Iterator(func(key, value any) bool { totalKey += key.(int) totalValue += value.(int) @@ -501,13 +501,13 @@ func ExampleRedBlackTree_Iterator() { } func ExampleRedBlackTree_IteratorFrom() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewRedBlackTreeFrom(gutil.ComparatorInt, m) - tree.IteratorFrom(1, true, func(key, value interface{}) bool { + tree.IteratorFrom(1, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -526,7 +526,7 @@ func ExampleRedBlackTree_IteratorAsc() { tree.Set(i, 10-i) } - tree.IteratorAsc(func(key, value interface{}) bool { + tree.IteratorAsc(func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -545,13 +545,13 @@ func ExampleRedBlackTree_IteratorAsc() { } func ExampleRedBlackTree_IteratorAscFrom_normal() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewRedBlackTreeFrom(gutil.ComparatorInt, m) - tree.IteratorAscFrom(1, true, func(key, value interface{}) bool { + tree.IteratorAscFrom(1, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -565,13 +565,13 @@ func ExampleRedBlackTree_IteratorAscFrom_normal() { } func ExampleRedBlackTree_IteratorAscFrom_noExistKey() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewRedBlackTreeFrom(gutil.ComparatorInt, m) - tree.IteratorAscFrom(0, true, func(key, value interface{}) bool { + tree.IteratorAscFrom(0, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -580,13 +580,13 @@ func ExampleRedBlackTree_IteratorAscFrom_noExistKey() { } func ExampleRedBlackTree_IteratorAscFrom_noExistKeyAndMatchFalse() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewRedBlackTreeFrom(gutil.ComparatorInt, m) - tree.IteratorAscFrom(0, false, func(key, value interface{}) bool { + tree.IteratorAscFrom(0, false, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -605,7 +605,7 @@ func ExampleRedBlackTree_IteratorDesc() { tree.Set(i, 10-i) } - tree.IteratorDesc(func(key, value interface{}) bool { + tree.IteratorDesc(func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -624,13 +624,13 @@ func ExampleRedBlackTree_IteratorDesc() { } func ExampleRedBlackTree_IteratorDescFrom() { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 5; i++ { m[i] = i * 10 } tree := gtree.NewRedBlackTreeFrom(gutil.ComparatorInt, m) - tree.IteratorDescFrom(5, true, func(key, value interface{}) bool { + tree.IteratorDescFrom(5, true, func(key, value any) bool { fmt.Println("key:", key, ", value:", value) return true }) @@ -666,7 +666,7 @@ func ExampleRedBlackTree_Replace() { fmt.Println(tree.Map()) - data := map[interface{}]interface{}{ + data := map[any]any{ "newKey0": "newVal0", "newKey1": "newVal1", "newKey2": "newVal2", diff --git a/container/gtree/gtree_z_redblack_tree_test.go b/container/gtree/gtree_z_redblack_tree_test.go index fd1a3caffbb..2989b44c5f9 100644 --- a/container/gtree/gtree_z_redblack_tree_test.go +++ b/container/gtree/gtree_z_redblack_tree_test.go @@ -16,7 +16,7 @@ import ( "github.com/gogf/gf/v2/util/gutil" ) -func getValue() interface{} { +func getValue() any { return 3 } @@ -24,7 +24,7 @@ func Test_RedBlackTree_Basic(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gtree.NewRedBlackTree(gutil.ComparatorString) m.Set("key1", "val1") - t.Assert(m.Keys(), []interface{}{"key1"}) + t.Assert(m.Keys(), []any{"key1"}) t.Assert(m.Get("key1"), "val1") t.Assert(m.Size(), 1) @@ -44,20 +44,20 @@ func Test_RedBlackTree_Basic(t *testing.T) { t.AssertIN("val3", m.Values()) t.AssertIN("val1", m.Values()) - m.Sets(map[interface{}]interface{}{"key3": "val3", "key1": "val1"}) + m.Sets(map[any]any{"key3": "val3", "key1": "val1"}) m.Flip() - t.Assert(m.Map(), map[interface{}]interface{}{"val3": "key3", "val1": "key1"}) + t.Assert(m.Map(), map[any]any{"val3": "key3", "val1": "key1"}) m.Flip(gutil.ComparatorString) - t.Assert(m.Map(), map[interface{}]interface{}{"key3": "val3", "key1": "val1"}) + t.Assert(m.Map(), map[any]any{"key3": "val3", "key1": "val1"}) m.Clear() t.Assert(m.Size(), 0) t.Assert(m.IsEmpty(), true) - m2 := gtree.NewRedBlackTreeFrom(gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) - t.Assert(m2.Map(), map[interface{}]interface{}{1: 1, "key1": "val1"}) + m2 := gtree.NewRedBlackTreeFrom(gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"}) + t.Assert(m2.Map(), map[any]any{1: 1, "key1": "val1"}) }) } @@ -106,10 +106,10 @@ func Test_RedBlackTree_Get_Set_Var(t *testing.T) { func Test_RedBlackTree_Batch(t *testing.T) { gtest.C(t, func(t *gtest.T) { m := gtree.NewRedBlackTree(gutil.ComparatorString) - m.Sets(map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - t.Assert(m.Map(), map[interface{}]interface{}{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) - m.Removes([]interface{}{"key1", 1}) - t.Assert(m.Map(), map[interface{}]interface{}{"key2": "val2", "key3": "val3"}) + m.Sets(map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + t.Assert(m.Map(), map[any]any{1: 1, "key1": "val1", "key2": "val2", "key3": "val3"}) + m.Removes([]any{"key1", 1}) + t.Assert(m.Map(), map[any]any{"key2": "val2", "key3": "val3"}) }) } @@ -118,19 +118,19 @@ func Test_RedBlackTree_Iterator(t *testing.T) { keyLen := len(keys) index := 0 - expect := map[interface{}]interface{}{"key4": "val4", 1: 1, "key1": "val1", "key2": "val2", "key3": "val3"} + expect := map[any]any{"key4": "val4", 1: 1, "key1": "val1", "key2": "val2", "key3": "val3"} m := gtree.NewRedBlackTreeFrom(gutil.ComparatorString, expect) gtest.C(t, func(t *gtest.T) { - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { t.Assert(k, keys[index]) index++ t.Assert(expect[k], v) return true }) - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { index-- t.Assert(k, keys[index]) t.Assert(expect[k], v) @@ -142,11 +142,11 @@ func Test_RedBlackTree_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { i := 0 j := 0 - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { i++ return true }) - m.Iterator(func(k interface{}, v interface{}) bool { + m.Iterator(func(k any, v any) bool { j++ return false }) @@ -157,11 +157,11 @@ func Test_RedBlackTree_Iterator(t *testing.T) { gtest.C(t, func(t *gtest.T) { i := 0 j := 0 - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { i++ return true }) - m.IteratorDesc(func(k interface{}, v interface{}) bool { + m.IteratorDesc(func(k any, v any) bool { j++ return false }) @@ -171,7 +171,7 @@ func Test_RedBlackTree_Iterator(t *testing.T) { } func Test_RedBlackTree_IteratorFrom(t *testing.T) { - m := make(map[interface{}]interface{}) + m := make(map[any]any) for i := 1; i <= 10; i++ { m[i] = i * 10 } @@ -179,7 +179,7 @@ func Test_RedBlackTree_IteratorFrom(t *testing.T) { gtest.C(t, func(t *gtest.T) { n := 5 - tree.IteratorFrom(5, true, func(key, value interface{}) bool { + tree.IteratorFrom(5, true, func(key, value any) bool { t.Assert(n, key) t.Assert(n*10, value) n++ @@ -187,7 +187,7 @@ func Test_RedBlackTree_IteratorFrom(t *testing.T) { }) i := 5 - tree.IteratorAscFrom(5, true, func(key, value interface{}) bool { + tree.IteratorAscFrom(5, true, func(key, value any) bool { t.Assert(i, key) t.Assert(i*10, value) i++ @@ -195,7 +195,7 @@ func Test_RedBlackTree_IteratorFrom(t *testing.T) { }) j := 5 - tree.IteratorDescFrom(5, true, func(key, value interface{}) bool { + tree.IteratorDescFrom(5, true, func(key, value any) bool { t.Assert(j, key) t.Assert(j*10, value) j-- @@ -207,7 +207,7 @@ func Test_RedBlackTree_IteratorFrom(t *testing.T) { func Test_RedBlackTree_Clone(t *testing.T) { gtest.C(t, func(t *gtest.T) { //clone 方法是深克隆 - m := gtree.NewRedBlackTreeFrom(gutil.ComparatorString, map[interface{}]interface{}{1: 1, "key1": "val1"}) + m := gtree.NewRedBlackTreeFrom(gutil.ComparatorString, map[any]any{1: 1, "key1": "val1"}) m_clone := m.Clone() m.Remove(1) //修改原 map,clone 后的 map 不影响 @@ -220,7 +220,7 @@ func Test_RedBlackTree_Clone(t *testing.T) { } func Test_RedBlackTree_LRNode(t *testing.T) { - expect := map[interface{}]interface{}{"key4": "val4", "key1": "val1", "key2": "val2", "key3": "val3"} + expect := map[any]any{"key4": "val4", "key1": "val1", "key2": "val2", "key3": "val3"} //safe gtest.C(t, func(t *gtest.T) { m := gtree.NewRedBlackTreeFrom(gutil.ComparatorString, expect) @@ -236,7 +236,7 @@ func Test_RedBlackTree_LRNode(t *testing.T) { } func Test_RedBlackTree_CeilingFloor(t *testing.T) { - expect := map[interface{}]interface{}{ + expect := map[any]any{ 20: "val20", 6: "val6", 10: "val10", diff --git a/container/gtype/gtype.go b/container/gtype/gtype.go index 2e6a112912e..a1c360beaed 100644 --- a/container/gtype/gtype.go +++ b/container/gtype/gtype.go @@ -9,6 +9,6 @@ package gtype // New is alias of NewAny. // See NewAny, NewInterface. -func New(value ...interface{}) *Any { +func New(value ...any) *Any { return NewAny(value...) } diff --git a/container/gtype/gtype_bool.go b/container/gtype/gtype_bool.go index b85dfd912f2..97993c30c5b 100644 --- a/container/gtype/gtype_bool.go +++ b/container/gtype/gtype_bool.go @@ -92,13 +92,13 @@ func (v *Bool) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Bool) UnmarshalValue(value interface{}) error { +func (v *Bool) UnmarshalValue(value any) error { v.Set(gconv.Bool(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Bool) DeepCopy() interface{} { +func (v *Bool) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_byte.go b/container/gtype/gtype_byte.go index 836231c5786..5015061dcf2 100644 --- a/container/gtype/gtype_byte.go +++ b/container/gtype/gtype_byte.go @@ -71,13 +71,13 @@ func (v *Byte) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Byte) UnmarshalValue(value interface{}) error { +func (v *Byte) UnmarshalValue(value any) error { v.Set(gconv.Byte(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Byte) DeepCopy() interface{} { +func (v *Byte) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_bytes.go b/container/gtype/gtype_bytes.go index e01ee4182a9..a389b28f017 100644 --- a/container/gtype/gtype_bytes.go +++ b/container/gtype/gtype_bytes.go @@ -79,13 +79,13 @@ func (v *Bytes) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Bytes) UnmarshalValue(value interface{}) error { +func (v *Bytes) UnmarshalValue(value any) error { v.Set(gconv.Bytes(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Bytes) DeepCopy() interface{} { +func (v *Bytes) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_float32.go b/container/gtype/gtype_float32.go index 82289abbd0e..6529b6c26e5 100644 --- a/container/gtype/gtype_float32.go +++ b/container/gtype/gtype_float32.go @@ -83,13 +83,13 @@ func (v *Float32) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Float32) UnmarshalValue(value interface{}) error { +func (v *Float32) UnmarshalValue(value any) error { v.Set(gconv.Float32(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Float32) DeepCopy() interface{} { +func (v *Float32) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_float64.go b/container/gtype/gtype_float64.go index ce44abd15bd..1bc13f667f6 100644 --- a/container/gtype/gtype_float64.go +++ b/container/gtype/gtype_float64.go @@ -83,13 +83,13 @@ func (v *Float64) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Float64) UnmarshalValue(value interface{}) error { +func (v *Float64) UnmarshalValue(value any) error { v.Set(gconv.Float64(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Float64) DeepCopy() interface{} { +func (v *Float64) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_int.go b/container/gtype/gtype_int.go index 32a610fbece..5aba64a7e16 100644 --- a/container/gtype/gtype_int.go +++ b/container/gtype/gtype_int.go @@ -71,13 +71,13 @@ func (v *Int) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Int) UnmarshalValue(value interface{}) error { +func (v *Int) UnmarshalValue(value any) error { v.Set(gconv.Int(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Int) DeepCopy() interface{} { +func (v *Int) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_int32.go b/container/gtype/gtype_int32.go index 58ad36a3bf7..4b67aefb736 100644 --- a/container/gtype/gtype_int32.go +++ b/container/gtype/gtype_int32.go @@ -71,13 +71,13 @@ func (v *Int32) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Int32) UnmarshalValue(value interface{}) error { +func (v *Int32) UnmarshalValue(value any) error { v.Set(gconv.Int32(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Int32) DeepCopy() interface{} { +func (v *Int32) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_int64.go b/container/gtype/gtype_int64.go index 54e72c12db4..2d780adfdff 100644 --- a/container/gtype/gtype_int64.go +++ b/container/gtype/gtype_int64.go @@ -71,13 +71,13 @@ func (v *Int64) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Int64) UnmarshalValue(value interface{}) error { +func (v *Int64) UnmarshalValue(value any) error { v.Set(gconv.Int64(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Int64) DeepCopy() interface{} { +func (v *Int64) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_interface.go b/container/gtype/gtype_interface.go index 9e57abb6fbe..bcaa61b3e19 100644 --- a/container/gtype/gtype_interface.go +++ b/container/gtype/gtype_interface.go @@ -14,14 +14,14 @@ import ( "github.com/gogf/gf/v2/util/gconv" ) -// Interface is a struct for concurrent-safe operation for type interface{}. +// Interface is a struct for concurrent-safe operation for type any. type Interface struct { value atomic.Value } -// NewInterface creates and returns a concurrent-safe object for interface{} type, +// NewInterface creates and returns a concurrent-safe object for any type, // with given initial value `value`. -func NewInterface(value ...interface{}) *Interface { +func NewInterface(value ...any) *Interface { t := &Interface{} if len(value) > 0 && value[0] != nil { t.value.Store(value[0]) @@ -29,21 +29,21 @@ func NewInterface(value ...interface{}) *Interface { return t } -// Clone clones and returns a new concurrent-safe object for interface{} type. +// Clone clones and returns a new concurrent-safe object for any type. func (v *Interface) Clone() *Interface { return NewInterface(v.Val()) } // Set atomically stores `value` into t.value and returns the previous value of t.value. // Note: The parameter `value` cannot be nil. -func (v *Interface) Set(value interface{}) (old interface{}) { +func (v *Interface) Set(value any) (old any) { old = v.Val() v.value.Store(value) return } // Val atomically loads and returns t.value. -func (v *Interface) Val() interface{} { +func (v *Interface) Val() any { return v.value.Load() } @@ -59,7 +59,7 @@ func (v Interface) MarshalJSON() ([]byte, error) { // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Interface) UnmarshalJSON(b []byte) error { - var i interface{} + var i any if err := json.UnmarshalUseNumber(b, &i); err != nil { return err } @@ -68,13 +68,13 @@ func (v *Interface) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Interface) UnmarshalValue(value interface{}) error { +func (v *Interface) UnmarshalValue(value any) error { v.Set(value) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Interface) DeepCopy() interface{} { +func (v *Interface) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_string.go b/container/gtype/gtype_string.go index b753e0faa13..5b78d38414c 100644 --- a/container/gtype/gtype_string.go +++ b/container/gtype/gtype_string.go @@ -66,13 +66,13 @@ func (v *String) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *String) UnmarshalValue(value interface{}) error { +func (v *String) UnmarshalValue(value any) error { v.Set(gconv.String(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *String) DeepCopy() interface{} { +func (v *String) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_uint.go b/container/gtype/gtype_uint.go index fa00f472d6d..041a95562b3 100644 --- a/container/gtype/gtype_uint.go +++ b/container/gtype/gtype_uint.go @@ -71,13 +71,13 @@ func (v *Uint) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Uint) UnmarshalValue(value interface{}) error { +func (v *Uint) UnmarshalValue(value any) error { v.Set(gconv.Uint(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Uint) DeepCopy() interface{} { +func (v *Uint) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_uint32.go b/container/gtype/gtype_uint32.go index 58df2e2cdf2..d337755e66b 100644 --- a/container/gtype/gtype_uint32.go +++ b/container/gtype/gtype_uint32.go @@ -71,13 +71,13 @@ func (v *Uint32) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Uint32) UnmarshalValue(value interface{}) error { +func (v *Uint32) UnmarshalValue(value any) error { v.Set(gconv.Uint32(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Uint32) DeepCopy() interface{} { +func (v *Uint32) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_uint64.go b/container/gtype/gtype_uint64.go index 3b54eb63c53..b39cd9a07b1 100644 --- a/container/gtype/gtype_uint64.go +++ b/container/gtype/gtype_uint64.go @@ -71,13 +71,13 @@ func (v *Uint64) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for `v`. -func (v *Uint64) UnmarshalValue(value interface{}) error { +func (v *Uint64) UnmarshalValue(value any) error { v.Set(gconv.Uint64(value)) return nil } // DeepCopy implements interface for deep copy of current type. -func (v *Uint64) DeepCopy() interface{} { +func (v *Uint64) DeepCopy() any { if v == nil { return nil } diff --git a/container/gtype/gtype_z_unit_bool_test.go b/container/gtype/gtype_z_unit_bool_test.go index 8174a250d65..20a5694c48f 100644 --- a/container/gtype/gtype_z_unit_bool_test.go +++ b/container/gtype/gtype_z_unit_bool_test.go @@ -116,7 +116,7 @@ func Test_Bool_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "true", }, &v) @@ -126,7 +126,7 @@ func Test_Bool_UnmarshalValue(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "false", }, &v) diff --git a/container/gtype/gtype_z_unit_byte_test.go b/container/gtype/gtype_z_unit_byte_test.go index 72f1fcee7ea..263d74e437b 100644 --- a/container/gtype/gtype_z_unit_byte_test.go +++ b/container/gtype/gtype_z_unit_byte_test.go @@ -78,7 +78,7 @@ func Test_Byte_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "2", }, &v) diff --git a/container/gtype/gtype_z_unit_bytes_test.go b/container/gtype/gtype_z_unit_bytes_test.go index 29e731c7740..055e4d6d26d 100644 --- a/container/gtype/gtype_z_unit_bytes_test.go +++ b/container/gtype/gtype_z_unit_bytes_test.go @@ -62,7 +62,7 @@ func Test_Bytes_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123", }, &v) diff --git a/container/gtype/gtype_z_unit_float32_test.go b/container/gtype/gtype_z_unit_float32_test.go index 26c5c584030..930830f0c2f 100644 --- a/container/gtype/gtype_z_unit_float32_test.go +++ b/container/gtype/gtype_z_unit_float32_test.go @@ -67,7 +67,7 @@ func Test_Float32_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123.456", }, &v) diff --git a/container/gtype/gtype_z_unit_float64_test.go b/container/gtype/gtype_z_unit_float64_test.go index 1bc6b27b976..25f53f5657d 100644 --- a/container/gtype/gtype_z_unit_float64_test.go +++ b/container/gtype/gtype_z_unit_float64_test.go @@ -65,7 +65,7 @@ func Test_Float64_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123.456", }, &v) diff --git a/container/gtype/gtype_z_unit_int32_test.go b/container/gtype/gtype_z_unit_int32_test.go index 445fabee94f..002811a9162 100644 --- a/container/gtype/gtype_z_unit_int32_test.go +++ b/container/gtype/gtype_z_unit_int32_test.go @@ -78,7 +78,7 @@ func Test_Int32_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123", }, &v) diff --git a/container/gtype/gtype_z_unit_int64_test.go b/container/gtype/gtype_z_unit_int64_test.go index 1233f0f45c8..e7cef9ec27d 100644 --- a/container/gtype/gtype_z_unit_int64_test.go +++ b/container/gtype/gtype_z_unit_int64_test.go @@ -77,7 +77,7 @@ func Test_Int64_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123", }, &v) diff --git a/container/gtype/gtype_z_unit_int_test.go b/container/gtype/gtype_z_unit_int_test.go index 5bbbdbbdb7e..09ee5628499 100644 --- a/container/gtype/gtype_z_unit_int_test.go +++ b/container/gtype/gtype_z_unit_int_test.go @@ -77,7 +77,7 @@ func Test_Int_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123", }, &v) diff --git a/container/gtype/gtype_z_unit_interface_test.go b/container/gtype/gtype_z_unit_interface_test.go index 29c66bb36d4..b091250f4cb 100644 --- a/container/gtype/gtype_z_unit_interface_test.go +++ b/container/gtype/gtype_z_unit_interface_test.go @@ -63,7 +63,7 @@ func Test_Interface_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123", }, &v) diff --git a/container/gtype/gtype_z_unit_string_test.go b/container/gtype/gtype_z_unit_string_test.go index a7769110a0d..027ed68703e 100644 --- a/container/gtype/gtype_z_unit_string_test.go +++ b/container/gtype/gtype_z_unit_string_test.go @@ -59,7 +59,7 @@ func Test_String_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123", }, &v) diff --git a/container/gtype/gtype_z_unit_uint32_test.go b/container/gtype/gtype_z_unit_uint32_test.go index d1989a6892e..0823862d749 100644 --- a/container/gtype/gtype_z_unit_uint32_test.go +++ b/container/gtype/gtype_z_unit_uint32_test.go @@ -77,7 +77,7 @@ func Test_Uint32_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123", }, &v) diff --git a/container/gtype/gtype_z_unit_uint64_test.go b/container/gtype/gtype_z_unit_uint64_test.go index 1cf407984be..d65de056967 100644 --- a/container/gtype/gtype_z_unit_uint64_test.go +++ b/container/gtype/gtype_z_unit_uint64_test.go @@ -82,7 +82,7 @@ func Test_Uint64_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123", }, &v) diff --git a/container/gtype/gtype_z_unit_uint_test.go b/container/gtype/gtype_z_unit_uint_test.go index e4b6b957c3f..b76e43112bd 100644 --- a/container/gtype/gtype_z_unit_uint_test.go +++ b/container/gtype/gtype_z_unit_uint_test.go @@ -76,7 +76,7 @@ func Test_Uint_UnmarshalValue(t *testing.T) { } gtest.C(t, func(t *gtest.T) { var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "123", }, &v) diff --git a/container/gvar/gvar.go b/container/gvar/gvar.go index 07cd9af69b6..0ea6d30c251 100644 --- a/container/gvar/gvar.go +++ b/container/gvar/gvar.go @@ -14,14 +14,14 @@ import ( // Var is an universal variable type implementer. type Var struct { - value interface{} // Underlying value. - safe bool // Concurrent safe or not. + value any // Underlying value. + safe bool // Concurrent safe or not. } // New creates and returns a new Var with given `value`. // The optional parameter `safe` specifies whether Var is used in concurrent-safety, // which is false in default. -func New(value interface{}, safe ...bool) *Var { +func New(value any, safe ...bool) *Var { if len(safe) > 0 && safe[0] { return &Var{ value: gtype.NewInterface(value), @@ -40,7 +40,7 @@ func (v *Var) MarshalJSON() ([]byte, error) { // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (v *Var) UnmarshalJSON(b []byte) error { - var i interface{} + var i any if err := json.UnmarshalUseNumber(b, &i); err != nil { return err } @@ -49,7 +49,7 @@ func (v *Var) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for Var. -func (v *Var) UnmarshalValue(value interface{}) error { +func (v *Var) UnmarshalValue(value any) error { v.Set(value) return nil } diff --git a/container/gvar/gvar_copy.go b/container/gvar/gvar_copy.go index a85d3748288..31c83234659 100644 --- a/container/gvar/gvar_copy.go +++ b/container/gvar/gvar_copy.go @@ -22,7 +22,7 @@ func (v *Var) Clone() *Var { } // DeepCopy implements interface for deep copy of current type. -func (v *Var) DeepCopy() interface{} { +func (v *Var) DeepCopy() any { if v == nil { return nil } diff --git a/container/gvar/gvar_list.go b/container/gvar/gvar_list.go index 1f24bca88fd..f0a59a03735 100644 --- a/container/gvar/gvar_list.go +++ b/container/gvar/gvar_list.go @@ -13,13 +13,13 @@ import ( // ListItemValues retrieves and returns the elements of all item struct/map with key `key`. // Note that the parameter `list` should be type of slice which contains elements of map or struct, // or else it returns an empty slice. -func (v *Var) ListItemValues(key interface{}) (values []interface{}) { +func (v *Var) ListItemValues(key any) (values []any) { return gutil.ListItemValues(v.Val(), key) } // ListItemValuesUnique retrieves and returns the unique elements of all struct/map with key `key`. // Note that the parameter `list` should be type of slice which contains elements of map or struct, // or else it returns an empty slice. -func (v *Var) ListItemValuesUnique(key string) []interface{} { +func (v *Var) ListItemValuesUnique(key string) []any { return gutil.ListItemValuesUnique(v.Val(), key) } diff --git a/container/gvar/gvar_map.go b/container/gvar/gvar_map.go index f56874d171e..3e4d538f65f 100644 --- a/container/gvar/gvar_map.go +++ b/container/gvar/gvar_map.go @@ -11,13 +11,13 @@ import "github.com/gogf/gf/v2/util/gconv" // MapOption specifies the option for map converting. type MapOption = gconv.MapOption -// Map converts and returns `v` as map[string]interface{}. -func (v *Var) Map(option ...MapOption) map[string]interface{} { +// Map converts and returns `v` as map[string]any. +func (v *Var) Map(option ...MapOption) map[string]any { return gconv.Map(v.Val(), option...) } // MapStrAny is like function Map, but implements the interface of MapStrAny. -func (v *Var) MapStrAny(option ...MapOption) map[string]interface{} { +func (v *Var) MapStrAny(option ...MapOption) map[string]any { return v.Map(option...) } @@ -39,9 +39,9 @@ func (v *Var) MapStrVar(option ...MapOption) map[string]*Var { return nil } -// MapDeep converts and returns `v` as map[string]interface{} recursively. +// MapDeep converts and returns `v` as map[string]any recursively. // Deprecated: used Map instead. -func (v *Var) MapDeep(tags ...string) map[string]interface{} { +func (v *Var) MapDeep(tags ...string) map[string]any { return gconv.MapDeep(v.Val(), tags...) } @@ -67,31 +67,31 @@ func (v *Var) MapStrVarDeep(tags ...string) map[string]*Var { // Maps converts and returns `v` as map[string]string. // See gconv.Maps. -func (v *Var) Maps(option ...MapOption) []map[string]interface{} { +func (v *Var) Maps(option ...MapOption) []map[string]any { return gconv.Maps(v.Val(), option...) } -// MapsDeep converts `value` to []map[string]interface{} recursively. +// MapsDeep converts `value` to []map[string]any recursively. // Deprecated: used Maps instead. -func (v *Var) MapsDeep(tags ...string) []map[string]interface{} { +func (v *Var) MapsDeep(tags ...string) []map[string]any { return gconv.MapsDeep(v.Val(), tags...) } // MapToMap converts any map type variable `params` to another map type variable `pointer`. // See gconv.MapToMap. -func (v *Var) MapToMap(pointer interface{}, mapping ...map[string]string) (err error) { +func (v *Var) MapToMap(pointer any, mapping ...map[string]string) (err error) { return gconv.MapToMap(v.Val(), pointer, mapping...) } // MapToMaps converts any map type variable `params` to another map type variable `pointer`. // See gconv.MapToMaps. -func (v *Var) MapToMaps(pointer interface{}, mapping ...map[string]string) (err error) { +func (v *Var) MapToMaps(pointer any, mapping ...map[string]string) (err error) { return gconv.MapToMaps(v.Val(), pointer, mapping...) } // MapToMapsDeep converts any map type variable `params` to another map type variable // `pointer` recursively. // See gconv.MapToMapsDeep. -func (v *Var) MapToMapsDeep(pointer interface{}, mapping ...map[string]string) (err error) { +func (v *Var) MapToMapsDeep(pointer any, mapping ...map[string]string) (err error) { return gconv.MapToMaps(v.Val(), pointer, mapping...) } diff --git a/container/gvar/gvar_scan.go b/container/gvar/gvar_scan.go index 5c38bfbfe6d..277d5094b6b 100644 --- a/container/gvar/gvar_scan.go +++ b/container/gvar/gvar_scan.go @@ -13,6 +13,6 @@ import ( // Scan automatically checks the type of `pointer` and converts value of Var to `pointer`. // // See gconv.Scan. -func (v *Var) Scan(pointer interface{}, mapping ...map[string]string) error { +func (v *Var) Scan(pointer any, mapping ...map[string]string) error { return gconv.Scan(v.Val(), pointer, mapping...) } diff --git a/container/gvar/gvar_set.go b/container/gvar/gvar_set.go index a00b2a627d4..ccc684ce773 100644 --- a/container/gvar/gvar_set.go +++ b/container/gvar/gvar_set.go @@ -11,7 +11,7 @@ import ( ) // Set sets `value` to `v`, and returns the old value. -func (v *Var) Set(value interface{}) (old interface{}) { +func (v *Var) Set(value any) (old any) { if v.safe { if t, ok := v.value.(*gtype.Interface); ok { old = t.Set(value) diff --git a/container/gvar/gvar_slice.go b/container/gvar/gvar_slice.go index 02a61aa2e26..629249c4f40 100644 --- a/container/gvar/gvar_slice.go +++ b/container/gvar/gvar_slice.go @@ -49,17 +49,17 @@ func (v *Var) Strings() []string { } // Interfaces converts and returns `v` as []interfaces{}. -func (v *Var) Interfaces() []interface{} { +func (v *Var) Interfaces() []any { return gconv.Interfaces(v.Val()) } // Slice is alias of Interfaces. -func (v *Var) Slice() []interface{} { +func (v *Var) Slice() []any { return v.Interfaces() } // Array is alias of Interfaces. -func (v *Var) Array() []interface{} { +func (v *Var) Array() []any { return v.Interfaces() } diff --git a/container/gvar/gvar_struct.go b/container/gvar/gvar_struct.go index 30ca794b48a..7dd493eb14f 100644 --- a/container/gvar/gvar_struct.go +++ b/container/gvar/gvar_struct.go @@ -13,11 +13,11 @@ import ( // Struct maps value of `v` to `pointer`. // The parameter `pointer` should be a pointer to a struct instance. // The parameter `mapping` is used to specify the key-to-attribute mapping rules. -func (v *Var) Struct(pointer interface{}, mapping ...map[string]string) error { +func (v *Var) Struct(pointer any, mapping ...map[string]string) error { return gconv.Struct(v.Val(), pointer, mapping...) } // Structs converts and returns `v` as given struct slice. -func (v *Var) Structs(pointer interface{}, mapping ...map[string]string) error { +func (v *Var) Structs(pointer any, mapping ...map[string]string) error { return gconv.Structs(v.Val(), pointer, mapping...) } diff --git a/container/gvar/gvar_vars.go b/container/gvar/gvar_vars.go index f566a782ded..af52f9c698d 100644 --- a/container/gvar/gvar_vars.go +++ b/container/gvar/gvar_vars.go @@ -21,8 +21,8 @@ func (vs Vars) Strings() (s []string) { return s } -// Interfaces converts and returns `vs` as []interface{}. -func (vs Vars) Interfaces() (s []interface{}) { +// Interfaces converts and returns `vs` as []any. +func (vs Vars) Interfaces() (s []any) { for _, v := range vs { s = append(s, v.Val()) } @@ -126,6 +126,6 @@ func (vs Vars) Uint64s() (s []uint64) { } // Scan converts `vs` to []struct/[]*struct. -func (vs Vars) Scan(pointer interface{}, mapping ...map[string]string) error { +func (vs Vars) Scan(pointer any, mapping ...map[string]string) error { return gconv.Structs(vs.Interfaces(), pointer, mapping...) } diff --git a/container/gvar/gvar_z_example_test.go b/container/gvar/gvar_z_example_test.go index ac007ceebf7..2911af9d997 100644 --- a/container/gvar/gvar_z_example_test.go +++ b/container/gvar/gvar_z_example_test.go @@ -173,7 +173,7 @@ func ExampleVar_UnmarshalJSON() { "Price": 300, "OnSale": true }`) - var v = gvar.New(map[string]interface{}{}) + var v = gvar.New(map[string]any{}) if err := json.Unmarshal(tmp, &v); err != nil { panic(err) } @@ -193,7 +193,7 @@ func ExampleVar_UnmarshalValue() { "sale": true, } - var v = gvar.New(map[string]interface{}{}) + var v = gvar.New(map[string]any{}) if err := v.UnmarshalValue(tmp); err != nil { panic(err) } diff --git a/container/gvar/gvar_z_unit_basic_test.go b/container/gvar/gvar_z_unit_basic_test.go index 80f93086555..c392a2eb53d 100644 --- a/container/gvar/gvar_z_unit_basic_test.go +++ b/container/gvar/gvar_z_unit_basic_test.go @@ -257,7 +257,7 @@ func Test_UnmarshalJson(t *testing.T) { Var *gvar.Var } var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "v", }, &v) @@ -271,7 +271,7 @@ func Test_UnmarshalJson(t *testing.T) { Var gvar.Var } var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "v", }, &v) @@ -288,7 +288,7 @@ func Test_UnmarshalValue(t *testing.T) { Var *gvar.Var } var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "v", }, &v) @@ -302,7 +302,7 @@ func Test_UnmarshalValue(t *testing.T) { Var gvar.Var } var v *V - err := gconv.Struct(map[string]interface{}{ + err := gconv.Struct(map[string]any{ "name": "john", "var": "v", }, &v) diff --git a/container/gvar/gvar_z_unit_list_test.go b/container/gvar/gvar_z_unit_list_test.go index ecb648e96cc..9891b71ba0b 100644 --- a/container/gvar/gvar_z_unit_list_test.go +++ b/container/gvar/gvar_z_unit_list_test.go @@ -67,7 +67,7 @@ func TestVar_ListItemValues_Struct(t *testing.T) { gtest.C(t, func(t *gtest.T) { type T struct { Id int - Score interface{} + Score any } listStruct := g.Slice{ T{1, 100}, diff --git a/container/gvar/gvar_z_unit_map_test.go b/container/gvar/gvar_z_unit_map_test.go index 8a47895afd7..b01f45e3e43 100644 --- a/container/gvar/gvar_z_unit_map_test.go +++ b/container/gvar/gvar_z_unit_map_test.go @@ -46,7 +46,7 @@ func TestVar_MapToMap(t *testing.T) { t.Assert(m2["1"], m1[1]) t.Assert(m2["2"], m1[2]) }) - // map[string]interface{} -> map[string]string + // map[string]any -> map[string]string gtest.C(t, func(t *gtest.T) { m1 := g.Map{ "k1": "v1", @@ -57,7 +57,7 @@ func TestVar_MapToMap(t *testing.T) { t.Assert(m2["k1"], m1["k1"]) t.Assert(m2["k2"], m1["k2"]) }) - // map[string]string -> map[string]interface{} + // map[string]string -> map[string]any gtest.C(t, func(t *gtest.T) { m1 := g.MapStrStr{ "k1": "v1", @@ -68,7 +68,7 @@ func TestVar_MapToMap(t *testing.T) { t.Assert(m2["k1"], m1["k1"]) t.Assert(m2["k2"], m1["k2"]) }) - // map[string]interface{} -> map[interface{}]interface{} + // map[string]any -> map[any]any gtest.C(t, func(t *gtest.T) { m1 := g.MapStrStr{ "k1": "v1", diff --git a/container/gvar/gvar_z_unit_vars_test.go b/container/gvar/gvar_z_unit_vars_test.go index f4dd83f1c86..4933f540c58 100644 --- a/container/gvar/gvar_z_unit_vars_test.go +++ b/container/gvar/gvar_z_unit_vars_test.go @@ -22,7 +22,7 @@ func TestVars(t *testing.T) { gvar.New(3), } t.AssertEQ(vs.Strings(), []string{"1", "2", "3"}) - t.AssertEQ(vs.Interfaces(), []interface{}{1, 2, 3}) + t.AssertEQ(vs.Interfaces(), []any{1, 2, 3}) t.AssertEQ(vs.Float32s(), []float32{1, 2, 3}) t.AssertEQ(vs.Float64s(), []float64{1, 2, 3}) t.AssertEQ(vs.Ints(), []int{1, 2, 3}) diff --git a/contrib/config/apollo/apollo.go b/contrib/config/apollo/apollo.go index 3c967c775c2..9fb76f92c9b 100644 --- a/contrib/config/apollo/apollo.go +++ b/contrib/config/apollo/apollo.go @@ -100,7 +100,7 @@ func (c *Client) Available(ctx context.Context, resource ...string) (ok bool) { // Pattern like: // "x.y.z" for map item. // "x.0.y" for slice item. -func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, err error) { +func (c *Client) Get(ctx context.Context, pattern string) (value any, err error) { if c.value.IsNil() { if err = c.updateLocalValue(ctx); err != nil { return nil, err @@ -112,7 +112,7 @@ func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, er // Data retrieves and returns all configuration data in current resource as map. // Note that this function may lead lots of memory usage if configuration data is too large, // you can implement this function if necessary. -func (c *Client) Data(ctx context.Context) (data map[string]interface{}, err error) { +func (c *Client) Data(ctx context.Context) (data map[string]any, err error) { if c.value.IsNil() { if err = c.updateLocalValue(ctx); err != nil { return nil, err @@ -134,7 +134,7 @@ func (c *Client) OnNewestChange(event *storage.FullChangeEvent) { func (c *Client) updateLocalValue(ctx context.Context) (err error) { var j = gjson.New(nil) cache := c.client.GetConfigCache(c.config.NamespaceName) - cache.Range(func(key, value interface{}) bool { + cache.Range(func(key, value any) bool { err = j.Set(gconv.String(key), value) if err != nil { return false diff --git a/contrib/config/consul/consul.go b/contrib/config/consul/consul.go index afb1cf29e80..1d63ce43111 100644 --- a/contrib/config/consul/consul.go +++ b/contrib/config/consul/consul.go @@ -90,7 +90,7 @@ func (c *Client) Available(ctx context.Context, resource ...string) (ok bool) { // Pattern like: // "x.y.z" for map item. // "x.0.y" for slice item. -func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, err error) { +func (c *Client) Get(ctx context.Context, pattern string) (value any, err error) { if c.value.IsNil() { if err = c.updateLocalValue(); err != nil { return nil, err @@ -102,7 +102,7 @@ func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, er // Data retrieves and returns all configuration data in current resource as map. // Note that this function may lead lots of memory usage if configuration data is too large, // you can implement this function if necessary. -func (c *Client) Data(ctx context.Context) (data map[string]interface{}, err error) { +func (c *Client) Data(ctx context.Context) (data map[string]any, err error) { if c.value.IsNil() { if err = c.updateLocalValue(); err != nil { return nil, err @@ -137,7 +137,7 @@ func (c *Client) addWatcher() (err error) { return nil } - plan, err := watch.Parse(map[string]interface{}{ + plan, err := watch.Parse(map[string]any{ "type": "key", "key": c.config.Path, }) @@ -145,7 +145,7 @@ func (c *Client) addWatcher() (err error) { return gerror.Wrapf(err, `watch config from consul path %+v failed`, c.config.Path) } - plan.Handler = func(idx uint64, raw interface{}) { + plan.Handler = func(idx uint64, raw any) { var v *api.KVPair if raw == nil { // nil is a valid return value diff --git a/contrib/config/kubecm/kubecm.go b/contrib/config/kubecm/kubecm.go index 2be721d6102..d1548171070 100644 --- a/contrib/config/kubecm/kubecm.go +++ b/contrib/config/kubecm/kubecm.go @@ -93,7 +93,7 @@ func (c *Client) Available(ctx context.Context, configMap ...string) (ok bool) { // Pattern like: // "x.y.z" for map item. // "x.0.y" for slice item. -func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, err error) { +func (c *Client) Get(ctx context.Context, pattern string) (value any, err error) { if c.value.IsNil() { if err = c.updateLocalValueAndWatch(ctx); err != nil { return nil, err @@ -105,7 +105,7 @@ func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, er // Data retrieves and returns all configuration data in current resource as map. // Note that this function may lead lots of memory usage if configuration data is too large, // you can implement this function if necessary. -func (c *Client) Data(ctx context.Context) (data map[string]interface{}, err error) { +func (c *Client) Data(ctx context.Context) (data map[string]any, err error) { if c.value.IsNil() { if err = c.updateLocalValueAndWatch(ctx); err != nil { return nil, err diff --git a/contrib/config/nacos/nacos.go b/contrib/config/nacos/nacos.go index a952fb3fb5f..1788b1ed53b 100644 --- a/contrib/config/nacos/nacos.go +++ b/contrib/config/nacos/nacos.go @@ -50,7 +50,7 @@ func New(ctx context.Context, config Config) (adapter gcfg.Adapter, err error) { value: g.NewVar(nil, true), } - client.client, err = clients.CreateConfigClient(map[string]interface{}{ + client.client, err = clients.CreateConfigClient(map[string]any{ "serverConfigs": config.ServerConfigs, "clientConfig": config.ClientConfig, }) @@ -83,7 +83,7 @@ func (c *Client) Available(ctx context.Context, resource ...string) (ok bool) { // Pattern like: // "x.y.z" for map item. // "x.0.y" for slice item. -func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, err error) { +func (c *Client) Get(ctx context.Context, pattern string) (value any, err error) { if c.value.IsNil() { if err = c.updateLocalValue(); err != nil { return nil, err @@ -95,7 +95,7 @@ func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, er // Data retrieves and returns all configuration data in current resource as map. // Note that this function may lead lots of memory usage if configuration data is too large, // you can implement this function if necessary. -func (c *Client) Data(ctx context.Context) (data map[string]interface{}, err error) { +func (c *Client) Data(ctx context.Context) (data map[string]any, err error) { if c.value.IsNil() { if err = c.updateLocalValue(); err != nil { return nil, err diff --git a/contrib/config/polaris/polaris.go b/contrib/config/polaris/polaris.go index 1f9d6ee0576..5ab4f554883 100644 --- a/contrib/config/polaris/polaris.go +++ b/contrib/config/polaris/polaris.go @@ -108,7 +108,7 @@ func (c *Client) Available(ctx context.Context, resource ...string) (ok bool) { // Pattern like: // "x.y.z" for map item. // "x.0.y" for slice item. -func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, err error) { +func (c *Client) Get(ctx context.Context, pattern string) (value any, err error) { if c.value.IsNil() { if err = c.updateLocalValueAndWatch(ctx); err != nil { return nil, err @@ -120,7 +120,7 @@ func (c *Client) Get(ctx context.Context, pattern string) (value interface{}, er // Data retrieves and returns all configuration data in current resource as map. // Note that this function may lead to lots of memory usage if configuration data are too large, // you can implement this function if necessary. -func (c *Client) Data(ctx context.Context) (data map[string]interface{}, err error) { +func (c *Client) Data(ctx context.Context) (data map[string]any, err error) { if c.value.IsNil() { if err = c.updateLocalValueAndWatch(ctx); err != nil { return nil, err diff --git a/contrib/drivers/clickhouse/clickhouse_convert.go b/contrib/drivers/clickhouse/clickhouse_convert.go index 7540bb04292..e4392bcecbd 100644 --- a/contrib/drivers/clickhouse/clickhouse_convert.go +++ b/contrib/drivers/clickhouse/clickhouse_convert.go @@ -18,7 +18,7 @@ import ( ) // ConvertValueForField converts value to the type of the record field. -func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) { +func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue any) (any, error) { switch itemValue := fieldValue.(type) { case time.Time: // If the time is zero, it then updates it to nil, diff --git a/contrib/drivers/clickhouse/clickhouse_do_delete.go b/contrib/drivers/clickhouse/clickhouse_do_delete.go index e75d213fc71..4fab98537bd 100644 --- a/contrib/drivers/clickhouse/clickhouse_do_delete.go +++ b/contrib/drivers/clickhouse/clickhouse_do_delete.go @@ -14,7 +14,7 @@ import ( ) // DoDelete does "DELETE FROM ... " statement for the table. -func (d *Driver) DoDelete(ctx context.Context, link gdb.Link, table string, condition string, args ...interface{}) (result sql.Result, err error) { +func (d *Driver) DoDelete(ctx context.Context, link gdb.Link, table string, condition string, args ...any) (result sql.Result, err error) { ctx = d.injectNeedParsedSql(ctx) return d.Core.DoDelete(ctx, link, table, condition, args...) } diff --git a/contrib/drivers/clickhouse/clickhouse_do_filter.go b/contrib/drivers/clickhouse/clickhouse_do_filter.go index bb2ca2a1793..0bac9fbea81 100644 --- a/contrib/drivers/clickhouse/clickhouse_do_filter.go +++ b/contrib/drivers/clickhouse/clickhouse_do_filter.go @@ -17,8 +17,8 @@ import ( // DoFilter handles the sql before posts it to database. func (d *Driver) DoFilter( - ctx context.Context, link gdb.Link, originSql string, args []interface{}, -) (newSql string, newArgs []interface{}, err error) { + ctx context.Context, link gdb.Link, originSql string, args []any, +) (newSql string, newArgs []any, err error) { if len(args) == 0 { return originSql, args, nil } diff --git a/contrib/drivers/clickhouse/clickhouse_do_insert.go b/contrib/drivers/clickhouse/clickhouse_do_insert.go index efa076305fb..6a3f4b7c251 100644 --- a/contrib/drivers/clickhouse/clickhouse_do_insert.go +++ b/contrib/drivers/clickhouse/clickhouse_do_insert.go @@ -58,7 +58,7 @@ func (d *Driver) DoInsert( } for i := 0; i < len(list); i++ { // Values that will be committed to underlying database driver. - params := make([]interface{}, 0) + params := make([]any, 0) for _, k := range keys { params = append(params, list[i][k]) } diff --git a/contrib/drivers/clickhouse/clickhouse_do_update.go b/contrib/drivers/clickhouse/clickhouse_do_update.go index b1d82e66c4d..3d071cc1471 100644 --- a/contrib/drivers/clickhouse/clickhouse_do_update.go +++ b/contrib/drivers/clickhouse/clickhouse_do_update.go @@ -14,7 +14,7 @@ import ( ) // DoUpdate does "UPDATE ... " statement for the table. -func (d *Driver) DoUpdate(ctx context.Context, link gdb.Link, table string, data interface{}, condition string, args ...interface{}) (result sql.Result, err error) { +func (d *Driver) DoUpdate(ctx context.Context, link gdb.Link, table string, data any, condition string, args ...any) (result sql.Result, err error) { ctx = d.injectNeedParsedSql(ctx) return d.Core.DoUpdate(ctx, link, table, data, condition, args...) } diff --git a/contrib/drivers/clickhouse/clickhouse_insert.go b/contrib/drivers/clickhouse/clickhouse_insert.go index f7b38a2a0cf..49bb679b61b 100644 --- a/contrib/drivers/clickhouse/clickhouse_insert.go +++ b/contrib/drivers/clickhouse/clickhouse_insert.go @@ -12,16 +12,16 @@ import ( ) // InsertIgnore Other queries for modifying data parts are not supported: REPLACE, MERGE, UPSERT, INSERT UPDATE. -func (d *Driver) InsertIgnore(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) { +func (d *Driver) InsertIgnore(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) { return nil, errUnsupportedInsertIgnore } // InsertAndGetId Other queries for modifying data parts are not supported: REPLACE, MERGE, UPSERT, INSERT UPDATE. -func (d *Driver) InsertAndGetId(ctx context.Context, table string, data interface{}, batch ...int) (int64, error) { +func (d *Driver) InsertAndGetId(ctx context.Context, table string, data any, batch ...int) (int64, error) { return 0, errUnsupportedInsertGetId } // Replace Other queries for modifying data parts are not supported: REPLACE, MERGE, UPSERT, INSERT UPDATE. -func (d *Driver) Replace(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) { +func (d *Driver) Replace(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) { return nil, errUnsupportedReplace } diff --git a/contrib/drivers/clickhouse/clickhouse_z_unit_test.go b/contrib/drivers/clickhouse/clickhouse_z_unit_test.go index caf82f77a28..e2b7f2ac2cc 100644 --- a/contrib/drivers/clickhouse/clickhouse_z_unit_test.go +++ b/contrib/drivers/clickhouse/clickhouse_z_unit_test.go @@ -392,28 +392,28 @@ func TestDriverClickhouse_Replace(t *testing.T) { func TestDriverClickhouse_DoFilter(t *testing.T) { rawSQL := "select * from visits where 1 = 1" this := Driver{} - replaceSQL, _, err := this.DoFilter(context.Background(), nil, rawSQL, []interface{}{1}) + replaceSQL, _, err := this.DoFilter(context.Background(), nil, rawSQL, []any{1}) gtest.AssertNil(err) gtest.AssertEQ(rawSQL, replaceSQL) // this SQL can't run ,clickhouse will report an error because there is no WHERE statement rawSQL = "update visit set url = '1'" - replaceSQL, _, err = this.DoFilter(context.Background(), nil, rawSQL, []interface{}{1}) + replaceSQL, _, err = this.DoFilter(context.Background(), nil, rawSQL, []any{1}) gtest.AssertNil(err) // this SQL can't run ,clickhouse will report an error because there is no WHERE statement rawSQL = "delete from visit" - replaceSQL, _, err = this.DoFilter(context.Background(), nil, rawSQL, []interface{}{1}) + replaceSQL, _, err = this.DoFilter(context.Background(), nil, rawSQL, []any{1}) gtest.AssertNil(err) ctx := this.injectNeedParsedSql(context.Background()) rawSQL = "UPDATE visit SET url = '1' WHERE url = '0'" - replaceSQL, _, err = this.DoFilter(ctx, nil, rawSQL, []interface{}{1}) + replaceSQL, _, err = this.DoFilter(ctx, nil, rawSQL, []any{1}) gtest.AssertNil(err) gtest.AssertEQ(replaceSQL, "ALTER TABLE visit UPDATE url = '1' WHERE url = '0'") rawSQL = "DELETE FROM visit WHERE url = '0'" - replaceSQL, _, err = this.DoFilter(ctx, nil, rawSQL, []interface{}{1}) + replaceSQL, _, err = this.DoFilter(ctx, nil, rawSQL, []any{1}) gtest.AssertNil(err) gtest.AssertEQ(replaceSQL, "ALTER TABLE visit DELETE WHERE url = '0'") } @@ -468,7 +468,7 @@ func TestDriverClickhouse_NilTime(t *testing.T) { Col4 string Col5 map[string]uint8 Col6 []string - Col7 []interface{} + Col7 []any Col8 *time.Time Col9 uuid.UUID Col10 *gtime.Time @@ -482,7 +482,7 @@ func TestDriverClickhouse_NilTime(t *testing.T) { insertData = append(insertData, &testNilTime{ Col4: "Inc.", Col9: uuid.New(), - Col7: []interface{}{ // Tuple(String, UInt8, Array(Map(String, String))) + Col7: []any{ // Tuple(String, UInt8, Array(Map(String, String))) "String Value", uint8(5), []map[string]string{ {"key": "value"}, {"key": "value"}, @@ -521,7 +521,7 @@ func TestDriverClickhouse_BatchInsert(t *testing.T) { "Col4": guid.S(), "Col5": map[string]uint8{"key": 1}, // Map(String, UInt8) "Col6": []string{"Q", "W", "E", "R", "T", "Y"}, // Array(String) - "Col7": []interface{}{ // Tuple(String, UInt8, Array(Map(String, String))) + "Col7": []any{ // Tuple(String, UInt8, Array(Map(String, String))) "String Value", uint8(5), []map[string]string{ {"key": "value"}, {"key": "value"}, @@ -561,7 +561,7 @@ func TestDriverClickhouse_TableFields(t *testing.T) { gtest.AssertNil(err) gtest.AssertNE(dataTypeTable, nil) - var result = map[string][]interface{}{ + var result = map[string][]any{ "Col1": {0, "Col1", "UInt8", false, "", "", "", "列1"}, "Col2": {1, "Col2", "String", true, "", "", "", "列2"}, "Col3": {2, "Col3", "FixedString(3)", false, "", "", "", "列3"}, diff --git a/contrib/drivers/dm/dm_convert.go b/contrib/drivers/dm/dm_convert.go index f17909d29c7..f17d92a3323 100644 --- a/contrib/drivers/dm/dm_convert.go +++ b/contrib/drivers/dm/dm_convert.go @@ -14,7 +14,7 @@ import ( ) // ConvertValueForField converts value to the type of the record field. -func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) { +func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue any) (any, error) { switch itemValue := fieldValue.(type) { // dm does not support time.Time, it so here converts it to time string that it supports. case time.Time: diff --git a/contrib/drivers/dm/dm_do_filter.go b/contrib/drivers/dm/dm_do_filter.go index 8f574aef0e5..9c1a5c57894 100644 --- a/contrib/drivers/dm/dm_do_filter.go +++ b/contrib/drivers/dm/dm_do_filter.go @@ -17,8 +17,8 @@ import ( // DoFilter deals with the sql string before commits it to underlying sql driver. func (d *Driver) DoFilter( - ctx context.Context, link gdb.Link, sql string, args []interface{}, -) (newSql string, newArgs []interface{}, err error) { + ctx context.Context, link gdb.Link, sql string, args []any, +) (newSql string, newArgs []any, err error) { // There should be no need to capitalize, because it has been done from field processing before newSql, _ = gregex.ReplaceString(`["\n\t]`, "", sql) newSql = gstr.ReplaceI(gstr.ReplaceI(newSql, "GROUP_CONCAT", "LISTAGG"), "SEPARATOR", ",") diff --git a/contrib/drivers/dm/dm_do_insert.go b/contrib/drivers/dm/dm_do_insert.go index de2b216a40f..1218ab900fb 100644 --- a/contrib/drivers/dm/dm_do_insert.go +++ b/contrib/drivers/dm/dm_do_insert.go @@ -67,7 +67,7 @@ func (d *Driver) doSave(ctx context.Context, // insertValues: Handle values that need to be inserted // updateValues: Handle values that need to be updated queryHolders = make([]string, oneLen) - queryValues = make([]interface{}, oneLen) + queryValues = make([]any, oneLen) insertKeys = make([]string, oneLen) insertValues = make([]string, oneLen) updateValues []string diff --git a/contrib/drivers/dm/dm_do_query.go b/contrib/drivers/dm/dm_do_query.go index e06c412a620..0a4d65c551b 100644 --- a/contrib/drivers/dm/dm_do_query.go +++ b/contrib/drivers/dm/dm_do_query.go @@ -10,7 +10,7 @@ package dm // 但是我发现 DoQuery 中会对 sql 会对 " " 达梦的安全字符 进行 / 转义,最后还是导致达梦无法正常解析 // However, I found that DoQuery() will perform / escape on sql with " " Dameng's safe characters, which ultimately caused Dameng to be unable to parse normally. // But processing in DoFilter() is OK -// func (d *Driver) DoQuery(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (gdb.Result, error) { +// func (d *Driver) DoQuery(ctx context.Context, link gdb.Link, sql string, args ...any) (gdb.Result, error) { // l, r := d.GetChars() // new := gstr.ReplaceI(sql, "INDEX", l+"INDEX"+r) // g.Dump("new:", new) diff --git a/contrib/drivers/dm/dm_z_unit_basic_test.go b/contrib/drivers/dm/dm_z_unit_basic_test.go index 5bede337c3a..7e0f9c976a5 100644 --- a/contrib/drivers/dm/dm_z_unit_basic_test.go +++ b/contrib/drivers/dm/dm_z_unit_basic_test.go @@ -82,7 +82,7 @@ func TestTableFields(t *testing.T) { tables := "A_tables" createInitTable(tables) gtest.C(t, func(t *gtest.T) { - var expect = map[string][]interface{}{ + var expect = map[string][]any{ "ID": {"BIGINT", false}, "ACCOUNT_NAME": {"VARCHAR", false}, "PWD_RESET": {"TINYINT", false}, @@ -372,7 +372,7 @@ func Test_DB_BatchInsert(t *testing.T) { }) gtest.C(t, func(t *gtest.T) { - // []interface{} + // []any r, err := db.Insert(ctx, table, g.Slice{ g.Map{ "ID": 500, diff --git a/contrib/drivers/mssql/mssql_do_filter.go b/contrib/drivers/mssql/mssql_do_filter.go index 6130b9e795e..1ed24724d3c 100644 --- a/contrib/drivers/mssql/mssql_do_filter.go +++ b/contrib/drivers/mssql/mssql_do_filter.go @@ -46,8 +46,8 @@ func init() { // DoFilter deals with the sql string before commits it to underlying sql driver. func (d *Driver) DoFilter( - ctx context.Context, link gdb.Link, sql string, args []interface{}, -) (newSql string, newArgs []interface{}, err error) { + ctx context.Context, link gdb.Link, sql string, args []any, +) (newSql string, newArgs []any, err error) { var index int // Convert placeholder char '?' to string "@px". newSql, err = gregex.ReplaceStringFunc("\\?", sql, func(s string) string { diff --git a/contrib/drivers/mssql/mssql_do_filter_test.go b/contrib/drivers/mssql/mssql_do_filter_test.go index 24e2c80e9ed..89c76edcf38 100644 --- a/contrib/drivers/mssql/mssql_do_filter_test.go +++ b/contrib/drivers/mssql/mssql_do_filter_test.go @@ -23,14 +23,14 @@ func TestDriver_DoFilter(t *testing.T) { ctx context.Context link gdb.Link sql string - args []interface{} + args []any } var tests []struct { name string fields fields args args wantNewSql string - wantNewArgs []interface{} + wantNewArgs []any wantErr bool } for _, tt := range tests { diff --git a/contrib/drivers/mssql/mssql_do_insert.go b/contrib/drivers/mssql/mssql_do_insert.go index 7b71dab42f1..5e467d73069 100644 --- a/contrib/drivers/mssql/mssql_do_insert.go +++ b/contrib/drivers/mssql/mssql_do_insert.go @@ -66,7 +66,7 @@ func (d *Driver) doSave(ctx context.Context, // insertValues: Handle values that need to be inserted // updateValues: Handle values that need to be updated queryHolders = make([]string, oneLen) - queryValues = make([]interface{}, oneLen) + queryValues = make([]any, oneLen) insertKeys = make([]string, oneLen) insertValues = make([]string, oneLen) updateValues []string diff --git a/contrib/drivers/mssql/mssql_z_unit_basic_test.go b/contrib/drivers/mssql/mssql_z_unit_basic_test.go index 7235f0b1653..d39116a3c12 100644 --- a/contrib/drivers/mssql/mssql_z_unit_basic_test.go +++ b/contrib/drivers/mssql/mssql_z_unit_basic_test.go @@ -65,7 +65,7 @@ func TestTableFields(t *testing.T) { gtest.C(t, func(t *gtest.T) { createTable("t_user") defer dropTable("t_user") - var expect = map[string][]interface{}{ + var expect = map[string][]any{ "ID": {"numeric(10,0)", false, "PRI", "", "", ""}, "PASSPORT": {"varchar(45)", true, "", "", "", ""}, "PASSWORD": {"varchar(32)", true, "", "", "", ""}, @@ -378,7 +378,7 @@ func Test_DB_BatchInsert(t *testing.T) { gtest.C(t, func(t *gtest.T) { table := createTable() defer dropTable(table) - // []interface{} + // []any r, err := db.Insert(ctx, table, g.Slice{ g.Map{ "id": 2, @@ -866,7 +866,7 @@ func Test_DB_ToXml(t *testing.T) { gtest.Fatal(err) } - resultXml := result["doc"].(map[string]interface{}) + resultXml := result["doc"].(map[string]any) if v, ok := resultXml["ID"]; ok { t.Assert(user.Id, v) } else { diff --git a/contrib/drivers/mysql/mysql_do_filter.go b/contrib/drivers/mysql/mysql_do_filter.go index aff546ab931..e1553dd0f8f 100644 --- a/contrib/drivers/mysql/mysql_do_filter.go +++ b/contrib/drivers/mysql/mysql_do_filter.go @@ -14,7 +14,7 @@ import ( // DoFilter handles the sql before posts it to database. func (d *Driver) DoFilter( - ctx context.Context, link gdb.Link, sql string, args []interface{}, -) (newSql string, newArgs []interface{}, err error) { + ctx context.Context, link gdb.Link, sql string, args []any, +) (newSql string, newArgs []any, err error) { return d.Core.DoFilter(ctx, link, sql, args) } diff --git a/contrib/drivers/mysql/mysql_z_unit_basic_test.go b/contrib/drivers/mysql/mysql_z_unit_basic_test.go index b56048bf199..1da272a8b02 100644 --- a/contrib/drivers/mysql/mysql_z_unit_basic_test.go +++ b/contrib/drivers/mysql/mysql_z_unit_basic_test.go @@ -33,25 +33,25 @@ func Test_Func_FormatSqlWithArgs(t *testing.T) { // mysql gtest.C(t, func(t *gtest.T) { var s string - s = gdb.FormatSqlWithArgs("select * from table where id>=? and sex=?", []interface{}{100, 1}) + s = gdb.FormatSqlWithArgs("select * from table where id>=? and sex=?", []any{100, 1}) t.Assert(s, "select * from table where id>=100 and sex=1") }) // mssql gtest.C(t, func(t *gtest.T) { var s string - s = gdb.FormatSqlWithArgs("select * from table where id>=@p1 and sex=@p2", []interface{}{100, 1}) + s = gdb.FormatSqlWithArgs("select * from table where id>=@p1 and sex=@p2", []any{100, 1}) t.Assert(s, "select * from table where id>=100 and sex=1") }) // pgsql gtest.C(t, func(t *gtest.T) { var s string - s = gdb.FormatSqlWithArgs("select * from table where id>=$1 and sex=$2", []interface{}{100, 1}) + s = gdb.FormatSqlWithArgs("select * from table where id>=$1 and sex=$2", []any{100, 1}) t.Assert(s, "select * from table where id>=100 and sex=1") }) // oracle gtest.C(t, func(t *gtest.T) { var s string - s = gdb.FormatSqlWithArgs("select * from table where id>=:v1 and sex=:v2", []interface{}{100, 1}) + s = gdb.FormatSqlWithArgs("select * from table where id>=:v1 and sex=:v2", []any{100, 1}) t.Assert(s, "select * from table where id>=100 and sex=1") }) } diff --git a/contrib/drivers/mysql/mysql_z_unit_core_test.go b/contrib/drivers/mysql/mysql_z_unit_core_test.go index 5dce861e1b2..60474060687 100644 --- a/contrib/drivers/mysql/mysql_z_unit_core_test.go +++ b/contrib/drivers/mysql/mysql_z_unit_core_test.go @@ -429,7 +429,7 @@ func Test_DB_BatchInsert(t *testing.T) { gtest.C(t, func(t *gtest.T) { table := createTable() defer dropTable(table) - // []interface{} + // []any r, err := db.Insert(ctx, table, g.Slice{ g.Map{ "id": 2, @@ -967,7 +967,7 @@ func Test_DB_ToXml(t *testing.T) { gtest.Fatal(err) } - resultXml := result["doc"].(map[string]interface{}) + resultXml := result["doc"].(map[string]any) if v, ok := resultXml["id"]; ok { t.Assert(user.Id, v) } else { diff --git a/contrib/drivers/mysql/mysql_z_unit_feature_model_builder_test.go b/contrib/drivers/mysql/mysql_z_unit_feature_model_builder_test.go index 97d7c5ee125..0d1920580ae 100644 --- a/contrib/drivers/mysql/mysql_z_unit_feature_model_builder_test.go +++ b/contrib/drivers/mysql/mysql_z_unit_feature_model_builder_test.go @@ -69,13 +69,13 @@ func Test_Model_Builder(t *testing.T) { b := m.Builder() type Query struct { - Id interface{} + Id any Nickname *gtime.Time } where, args := b.Where(&Query{Id: 1}).Build() t.Assert(where, "`id`=? AND `nickname` IS NULL") - t.Assert(args, []interface{}{1}) + t.Assert(args, []any{1}) }) // Where with struct which has a field type of *gjson.Json @@ -84,13 +84,13 @@ func Test_Model_Builder(t *testing.T) { b := m.Builder() type Query struct { - Id interface{} + Id any Nickname *gjson.Json } where, args := b.Where(&Query{Id: 1}).Build() t.Assert(where, "`id`=? AND `nickname` IS NULL") - t.Assert(args, []interface{}{1}) + t.Assert(args, []any{1}) }) // Where with do struct which has a field type of *gtime.Time and generated by gf cli @@ -100,13 +100,13 @@ func Test_Model_Builder(t *testing.T) { type Query struct { gmeta.Meta `orm:"do:true"` - Id interface{} + Id any Nickname *gtime.Time } where, args := b.Where(&Query{Id: 1}).Build() t.Assert(where, "`id`=?") - t.Assert(args, []interface{}{1}) + t.Assert(args, []any{1}) }) // Where with do struct which has a field type of *gjson.Json and generated by gf cli @@ -116,13 +116,13 @@ func Test_Model_Builder(t *testing.T) { type Query struct { gmeta.Meta `orm:"do:true"` - Id interface{} + Id any Nickname *gjson.Json } where, args := b.Where(&Query{Id: 1}).Build() t.Assert(where, "`id`=?") - t.Assert(args, []interface{}{1}) + t.Assert(args, []any{1}) }) } diff --git a/contrib/drivers/mysql/mysql_z_unit_feature_model_do_test.go b/contrib/drivers/mysql/mysql_z_unit_feature_model_do_test.go index 27a08eab348..5ed5a4c719d 100644 --- a/contrib/drivers/mysql/mysql_z_unit_feature_model_do_test.go +++ b/contrib/drivers/mysql/mysql_z_unit_feature_model_do_test.go @@ -22,11 +22,11 @@ func Test_Model_Insert_Data_DO(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } data := User{ Id: 1, @@ -55,11 +55,11 @@ func Test_Model_Insert_Data_List_DO(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } data := g.Slice{ User{ @@ -103,11 +103,11 @@ func Test_Model_Update_Data_DO(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } data := User{ Id: 1, @@ -140,11 +140,11 @@ func Test_Model_Update_Pointer_Data_DO(t *testing.T) { } type UserDo struct { g.Meta `orm:"do:true"` - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } var ( nickname = NN("nickname_111") @@ -177,11 +177,11 @@ func Test_Model_Where_DO(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } where := User{ Id: 1, @@ -203,11 +203,11 @@ func Test_Model_Insert_Data_ForDao(t *testing.T) { gtest.C(t, func(t *gtest.T) { type UserForDao struct { - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } data := UserForDao{ Id: 1, @@ -235,11 +235,11 @@ func Test_Model_Insert_Data_List_ForDao(t *testing.T) { gtest.C(t, func(t *gtest.T) { type UserForDao struct { - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } data := g.Slice{ UserForDao{ @@ -282,11 +282,11 @@ func Test_Model_Update_Data_ForDao(t *testing.T) { gtest.C(t, func(t *gtest.T) { type UserForDao struct { - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } data := UserForDao{ Id: 1, @@ -311,11 +311,11 @@ func Test_Model_Where_ForDao(t *testing.T) { gtest.C(t, func(t *gtest.T) { type UserForDao struct { - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } where := UserForDao{ Id: 1, @@ -348,7 +348,7 @@ func Test_Model_Where_FieldPrefix(t *testing.T) { type InstanceDo struct { g.Meta `orm:"table:instance, do:true"` - ID interface{} `orm:"f_id"` + ID any `orm:"f_id"` } var instance *Instance err := db.Model("instance").Where(InstanceDo{ @@ -376,7 +376,7 @@ func Test_Model_Where_FieldPrefix(t *testing.T) { type InstanceDo struct { g.Meta `orm:"table:instance, do:true"` - ID interface{} `orm:"f_id,omitempty"` + ID any `orm:"f_id,omitempty"` } var instance *Instance err := db.Model("instance").Where(InstanceDo{ diff --git a/contrib/drivers/mysql/mysql_z_unit_feature_model_struct_test.go b/contrib/drivers/mysql/mysql_z_unit_feature_model_struct_test.go index 1463c4080db..3a687621615 100644 --- a/contrib/drivers/mysql/mysql_z_unit_feature_model_struct_test.go +++ b/contrib/drivers/mysql/mysql_z_unit_feature_model_struct_test.go @@ -337,7 +337,7 @@ type MyTimeSt struct { CreateTime MyTime } -func (st *MyTimeSt) UnmarshalValue(v interface{}) error { +func (st *MyTimeSt) UnmarshalValue(v any) error { m := gconv.Map(v) t, err := gtime.StrToTime(gconv.String(m["create_time"])) if err != nil { @@ -398,7 +398,7 @@ type User struct { CreateTime *gtime.Time } -func (user *User) UnmarshalValue(value interface{}) error { +func (user *User) UnmarshalValue(value any) error { if record, ok := value.(gdb.Record); ok { *user = User{ Id: record["id"].Int(), diff --git a/contrib/drivers/mysql/mysql_z_unit_feature_soft_time_test.go b/contrib/drivers/mysql/mysql_z_unit_feature_soft_time_test.go index cc5ac4f4db8..0ae94c91c24 100644 --- a/contrib/drivers/mysql/mysql_z_unit_feature_soft_time_test.go +++ b/contrib/drivers/mysql/mysql_z_unit_feature_soft_time_test.go @@ -636,11 +636,11 @@ CREATE TABLE %s ( time.Sleep(2 * time.Second) type User struct { g.Meta `orm:"do:true"` - Id interface{} - Num interface{} - CreatedAt interface{} - UpdatedAt interface{} - DeletedAt interface{} + Id any + Num any + CreatedAt any + UpdatedAt any + DeletedAt any } r, err = db.Model(table).Data(User{ Num: 100, diff --git a/contrib/drivers/mysql/mysql_z_unit_issue_test.go b/contrib/drivers/mysql/mysql_z_unit_issue_test.go index 7f7f0a85401..a4ce33e7abc 100644 --- a/contrib/drivers/mysql/mysql_z_unit_issue_test.go +++ b/contrib/drivers/mysql/mysql_z_unit_issue_test.go @@ -831,11 +831,11 @@ func Test_Issue2561(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } data := g.Slice{ User{ @@ -994,11 +994,11 @@ func Test_Issue3086(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } data := g.Slice{ User{ @@ -1016,11 +1016,11 @@ func Test_Issue3086(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} - Passport interface{} - Password interface{} - Nickname interface{} - CreateTime interface{} + Id any + Passport any + Password any + Nickname any + CreateTime any } data := g.Slice{ User{ @@ -1049,11 +1049,11 @@ func Test_Issue3204(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} `orm:"id,omitempty"` - Passport interface{} `orm:"passport,omitempty"` - Password interface{} `orm:"password,omitempty"` - Nickname interface{} `orm:"nickname,omitempty"` - CreateTime interface{} `orm:"create_time,omitempty"` + Id any `orm:"id,omitempty"` + Passport any `orm:"passport,omitempty"` + Password any `orm:"password,omitempty"` + Nickname any `orm:"nickname,omitempty"` + CreateTime any `orm:"create_time,omitempty"` } where := User{ Id: 2, @@ -1068,11 +1068,11 @@ func Test_Issue3204(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} `orm:"id,omitempty"` - Passport interface{} `orm:"passport,omitempty"` - Password interface{} `orm:"password,omitempty"` - Nickname interface{} `orm:"nickname,omitempty"` - CreateTime interface{} `orm:"create_time,omitempty"` + Id any `orm:"id,omitempty"` + Passport any `orm:"passport,omitempty"` + Password any `orm:"password,omitempty"` + Nickname any `orm:"nickname,omitempty"` + CreateTime any `orm:"create_time,omitempty"` } var ( err error @@ -1099,11 +1099,11 @@ func Test_Issue3204(t *testing.T) { gtest.C(t, func(t *gtest.T) { type User struct { g.Meta `orm:"do:true"` - Id interface{} `orm:"id,omitempty"` - Passport interface{} `orm:"passport,omitempty"` - Password interface{} `orm:"password,omitempty"` - Nickname interface{} `orm:"nickname,omitempty"` - CreateTime interface{} `orm:"create_time,omitempty"` + Id any `orm:"id,omitempty"` + Passport any `orm:"passport,omitempty"` + Password any `orm:"password,omitempty"` + Nickname any `orm:"nickname,omitempty"` + CreateTime any `orm:"create_time,omitempty"` } var ( err error diff --git a/contrib/drivers/oracle/oracle_do_filter.go b/contrib/drivers/oracle/oracle_do_filter.go index 0f952857cf0..2017306fb81 100644 --- a/contrib/drivers/oracle/oracle_do_filter.go +++ b/contrib/drivers/oracle/oracle_do_filter.go @@ -34,7 +34,7 @@ func init() { } // DoFilter deals with the sql string before commits it to underlying sql driver. -func (d *Driver) DoFilter(ctx context.Context, link gdb.Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) { +func (d *Driver) DoFilter(ctx context.Context, link gdb.Link, sql string, args []any) (newSql string, newArgs []any, err error) { var index int newArgs = args // Convert placeholder char '?' to string ":vx". diff --git a/contrib/drivers/oracle/oracle_do_insert.go b/contrib/drivers/oracle/oracle_do_insert.go index cf6a9b14bbb..d59bdf95b26 100644 --- a/contrib/drivers/oracle/oracle_do_insert.go +++ b/contrib/drivers/oracle/oracle_do_insert.go @@ -37,7 +37,7 @@ func (d *Driver) DoInsert( var ( keys []string values []string - params []interface{} + params []any ) // Retrieve the table fields and length. var ( @@ -123,7 +123,7 @@ func (d *Driver) doSave(ctx context.Context, // insertValues: Handle values that need to be inserted // updateValues: Handle values that need to be updated queryHolders = make([]string, oneLen) - queryValues = make([]interface{}, oneLen) + queryValues = make([]any, oneLen) insertKeys = make([]string, oneLen) insertValues = make([]string, oneLen) updateValues []string diff --git a/contrib/drivers/oracle/oracle_z_unit_basic_test.go b/contrib/drivers/oracle/oracle_z_unit_basic_test.go index b5cba3945bf..7a0af262455 100644 --- a/contrib/drivers/oracle/oracle_z_unit_basic_test.go +++ b/contrib/drivers/oracle/oracle_z_unit_basic_test.go @@ -63,7 +63,7 @@ func Test_Table_Fields(t *testing.T) { gtest.C(t, func(t *gtest.T) { createTable("t_user") defer dropTable("t_user") - var expect = map[string][]interface{}{ + var expect = map[string][]any{ "ID": {"INT(10,0)", false}, "PASSPORT": {"VARCHAR2(45)", false}, "PASSWORD": {"CHAR(32)", false}, @@ -330,7 +330,7 @@ func Test_DB_BatchInsert(t *testing.T) { gtest.C(t, func(t *gtest.T) { table := createTable() defer dropTable(table) - // []interface{} + // []any r, err := db.Insert(ctx, table, g.Slice{ g.Map{ "ID": 2, diff --git a/contrib/drivers/pgsql/pgsql_convert.go b/contrib/drivers/pgsql/pgsql_convert.go index c83a1e02918..00e1e92fa40 100644 --- a/contrib/drivers/pgsql/pgsql_convert.go +++ b/contrib/drivers/pgsql/pgsql_convert.go @@ -21,7 +21,7 @@ import ( ) // ConvertValueForField converts value to database acceptable value. -func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) { +func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue any) (any, error) { if g.IsNil(fieldValue) { return d.Core.ConvertValueForField(ctx, fieldType, fieldValue) } @@ -43,7 +43,7 @@ func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fie } // CheckLocalTypeForField checks and returns corresponding local golang type for given db type. -func (d *Driver) CheckLocalTypeForField(ctx context.Context, fieldType string, fieldValue interface{}) (gdb.LocalType, error) { +func (d *Driver) CheckLocalTypeForField(ctx context.Context, fieldType string, fieldValue any) (gdb.LocalType, error) { var typeName string match, _ := gregex.MatchString(`(.+?)\((.+)\)`, fieldType) if len(match) == 3 { @@ -86,7 +86,7 @@ func (d *Driver) CheckLocalTypeForField(ctx context.Context, fieldType string, f // ConvertValueForLocal converts value to local Golang type of value according field type name from database. // The parameter `fieldType` is in lower case, like: // `float(5,2)`, `unsigned double(5,2)`, `decimal(10,2)`, `char(45)`, `varchar(100)`, etc. -func (d *Driver) ConvertValueForLocal(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) { +func (d *Driver) ConvertValueForLocal(ctx context.Context, fieldType string, fieldValue any) (any, error) { typeName, _ := gregex.ReplaceString(`\(.+\)`, "", fieldType) typeName = strings.ToLower(typeName) switch typeName { diff --git a/contrib/drivers/pgsql/pgsql_do_exec.go b/contrib/drivers/pgsql/pgsql_do_exec.go index a44721752b0..f0d53371c69 100644 --- a/contrib/drivers/pgsql/pgsql_do_exec.go +++ b/contrib/drivers/pgsql/pgsql_do_exec.go @@ -19,7 +19,7 @@ import ( // DoExec commits the sql string and its arguments to underlying driver // through given link object and returns the execution result. -func (d *Driver) DoExec(ctx context.Context, link gdb.Link, sql string, args ...interface{}) (result sql.Result, err error) { +func (d *Driver) DoExec(ctx context.Context, link gdb.Link, sql string, args ...any) (result sql.Result, err error) { var ( isUseCoreDoExec bool = false // Check whether the default method needs to be used primaryKey string = "" diff --git a/contrib/drivers/pgsql/pgsql_do_filter.go b/contrib/drivers/pgsql/pgsql_do_filter.go index a04ed9a08d3..3769af4c36c 100644 --- a/contrib/drivers/pgsql/pgsql_do_filter.go +++ b/contrib/drivers/pgsql/pgsql_do_filter.go @@ -17,8 +17,8 @@ import ( // DoFilter deals with the sql string before commits it to underlying sql driver. func (d *Driver) DoFilter( - ctx context.Context, link gdb.Link, sql string, args []interface{}, -) (newSql string, newArgs []interface{}, err error) { + ctx context.Context, link gdb.Link, sql string, args []any, +) (newSql string, newArgs []any, err error) { var index int // Convert placeholder char '?' to string "$x". newSql, err = gregex.ReplaceStringFunc(`\?`, sql, func(s string) string { diff --git a/contrib/drivers/pgsql/pgsql_z_unit_db_test.go b/contrib/drivers/pgsql/pgsql_z_unit_db_test.go index 688301cd4c1..3dd264c9cce 100644 --- a/contrib/drivers/pgsql/pgsql_z_unit_db_test.go +++ b/contrib/drivers/pgsql/pgsql_z_unit_db_test.go @@ -301,7 +301,7 @@ func Test_DB_TableFields(t *testing.T) { table := createTable() defer dropTable(table) - var expect = map[string][]interface{}{ + var expect = map[string][]any{ //[]string: Index Type Null Key Default Comment //id is bigserial so the default is a pgsql function "id": {0, "int8", false, "pri", fmt.Sprintf("nextval('%s_id_seq'::regclass)", table), ""}, diff --git a/contrib/drivers/pgsql/pgsql_z_unit_issue_test.go b/contrib/drivers/pgsql/pgsql_z_unit_issue_test.go index c0c9ad8f25b..6fd5817fa24 100644 --- a/contrib/drivers/pgsql/pgsql_z_unit_issue_test.go +++ b/contrib/drivers/pgsql/pgsql_z_unit_issue_test.go @@ -39,7 +39,7 @@ func Test_Issue3330(t *testing.T) { gtest.C(t, func(t *gtest.T) { var ( - list []map[string]interface{} + list []map[string]any one gdb.Record err error ) @@ -145,8 +145,8 @@ func Test_Issue3671(t *testing.T) { // https://github.com/gogf/gf/issues/3668 func Test_Issue3668(t *testing.T) { type Issue3668 struct { - Text interface{} - Number interface{} + Text any + Number any } var ( sqlText = gtest.DataContent("issues", "issue3668.sql") diff --git a/contrib/drivers/sqlite/sqlite_do_filter.go b/contrib/drivers/sqlite/sqlite_do_filter.go index 3547b800eb1..0902e4e49ef 100644 --- a/contrib/drivers/sqlite/sqlite_do_filter.go +++ b/contrib/drivers/sqlite/sqlite_do_filter.go @@ -15,8 +15,8 @@ import ( // DoFilter deals with the sql string before commits it to underlying sql driver. func (d *Driver) DoFilter( - ctx context.Context, link gdb.Link, sql string, args []interface{}, -) (newSql string, newArgs []interface{}, err error) { + ctx context.Context, link gdb.Link, sql string, args []any, +) (newSql string, newArgs []any, err error) { // Special insert/ignore operation for sqlite. switch { case gstr.HasPrefix(sql, gdb.InsertOperationIgnore): diff --git a/contrib/drivers/sqlite/sqlite_open.go b/contrib/drivers/sqlite/sqlite_open.go index 0f084292c62..1374fa814cd 100644 --- a/contrib/drivers/sqlite/sqlite_open.go +++ b/contrib/drivers/sqlite/sqlite_open.go @@ -36,7 +36,7 @@ func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) { if config.Extra != "" { var ( options string - extraMap map[string]interface{} + extraMap map[string]any ) if extraMap, err = gstr.Parse(config.Extra); err != nil { return nil, err diff --git a/contrib/drivers/sqlite/sqlite_z_unit_core_test.go b/contrib/drivers/sqlite/sqlite_z_unit_core_test.go index f0ed23bbe9e..6d02ee678e1 100644 --- a/contrib/drivers/sqlite/sqlite_z_unit_core_test.go +++ b/contrib/drivers/sqlite/sqlite_z_unit_core_test.go @@ -358,7 +358,7 @@ func Test_DB_BatchInsert(t *testing.T) { gtest.C(t, func(t *gtest.T) { table := createTable() defer dropTable(table) - // []interface{} + // []any r, err := db.Insert(ctx, table, g.Slice{ g.Map{ "id": 2, @@ -904,7 +904,7 @@ func Test_DB_ToXml(t *testing.T) { gtest.Fatal(err) } - resultXml := result["doc"].(map[string]interface{}) + resultXml := result["doc"].(map[string]any) if v, ok := resultXml["id"]; ok { t.Assert(user.Id, v) } else { @@ -1543,7 +1543,7 @@ func Test_TableFields(t *testing.T) { tableName := "fields_" + gtime.TimestampNanoStr() createTable(tableName) defer dropTable(tableName) - var expect = map[string][]interface{}{ + var expect = map[string][]any{ // fields type null key default extra comment "id": {"INTEGER", false, "pri", nil, "", ""}, "passport": {"VARCHAR(45)", false, "", "passport", "", ""}, diff --git a/contrib/drivers/sqlitecgo/sqlitecgo_do_filter.go b/contrib/drivers/sqlitecgo/sqlitecgo_do_filter.go index 476ae1a0e97..8b728c12115 100644 --- a/contrib/drivers/sqlitecgo/sqlitecgo_do_filter.go +++ b/contrib/drivers/sqlitecgo/sqlitecgo_do_filter.go @@ -15,8 +15,8 @@ import ( // DoFilter deals with the sql string before commits it to underlying sql driver. func (d *Driver) DoFilter( - ctx context.Context, link gdb.Link, sql string, args []interface{}, -) (newSql string, newArgs []interface{}, err error) { + ctx context.Context, link gdb.Link, sql string, args []any, +) (newSql string, newArgs []any, err error) { // Special insert/ignore operation for sqlite. switch { case gstr.HasPrefix(sql, gdb.InsertOperationIgnore): diff --git a/contrib/drivers/sqlitecgo/sqlitecgo_open.go b/contrib/drivers/sqlitecgo/sqlitecgo_open.go index 1e2e4b985cc..8b7dfa5dbc9 100644 --- a/contrib/drivers/sqlitecgo/sqlitecgo_open.go +++ b/contrib/drivers/sqlitecgo/sqlitecgo_open.go @@ -45,7 +45,7 @@ func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) { if config.Extra != "" { var ( options string - extraMap map[string]interface{} + extraMap map[string]any ) if extraMap, err = gstr.Parse(config.Extra); err != nil { return nil, err diff --git a/contrib/drivers/sqlitecgo/sqlitecgo_z_unit_core_test.go b/contrib/drivers/sqlitecgo/sqlitecgo_z_unit_core_test.go index eb4396c92b0..8c4e467c108 100644 --- a/contrib/drivers/sqlitecgo/sqlitecgo_z_unit_core_test.go +++ b/contrib/drivers/sqlitecgo/sqlitecgo_z_unit_core_test.go @@ -358,7 +358,7 @@ func Test_DB_BatchInsert(t *testing.T) { gtest.C(t, func(t *gtest.T) { table := createTable() defer dropTable(table) - // []interface{} + // []any r, err := db.Insert(ctx, table, g.Slice{ g.Map{ "id": 2, @@ -904,7 +904,7 @@ func Test_DB_ToXml(t *testing.T) { gtest.Fatal(err) } - resultXml := result["doc"].(map[string]interface{}) + resultXml := result["doc"].(map[string]any) if v, ok := resultXml["id"]; ok { t.Assert(user.Id, v) } else { @@ -1543,7 +1543,7 @@ func Test_TableFields(t *testing.T) { tableName := "fields_" + gtime.TimestampNanoStr() createTable(tableName) defer dropTable(tableName) - var expect = map[string][]interface{}{ + var expect = map[string][]any{ // fields type null key default extra comment "id": {"INTEGER", false, "pri", nil, "", ""}, "passport": {"VARCHAR(45)", false, "", "passport", "", ""}, diff --git a/contrib/nosql/redis/redis_conn.go b/contrib/nosql/redis/redis_conn.go index 191adb71ac6..ece2fd3a96d 100644 --- a/contrib/nosql/redis/redis_conn.go +++ b/contrib/nosql/redis/redis_conn.go @@ -39,7 +39,7 @@ type Conn struct { type traceItem struct { err error command string - args []interface{} + args []any costMilli int64 } @@ -55,7 +55,7 @@ const ( // Do send a command to the server and returns the received reply. // It uses json.Marshal for struct/slice/map type values before committing them to redis. -func (c *Conn) Do(ctx context.Context, command string, args ...interface{}) (reply *gvar.Var, err error) { +func (c *Conn) Do(ctx context.Context, command string, args ...any) (reply *gvar.Var, err error) { if ctx == nil { ctx = context.Background() } @@ -99,7 +99,7 @@ func (c *Conn) Do(ctx context.Context, command string, args ...interface{}) (rep // Do send a command to the server and returns the received reply. // It uses json.Marshal for struct/slice/map type values before committing them to redis. -func (c *Conn) doCommand(ctx context.Context, command string, args ...interface{}) (reply *gvar.Var, err error) { +func (c *Conn) doCommand(ctx context.Context, command string, args ...any) (reply *gvar.Var, err error) { argStrSlice := gconv.Strings(args) switch gstr.ToLower(command) { case `subscribe`: @@ -125,8 +125,8 @@ func (c *Conn) doCommand(ctx context.Context, command string, args ...interface{ } default: - arguments := make([]interface{}, len(args)+1) - copy(arguments, []interface{}{command}) + arguments := make([]any, len(args)+1) + copy(arguments, []any{command}) copy(arguments[1:], args) reply, err = c.resultToVar(c.redis.client.Do(ctx, arguments...).Result()) if err != nil { @@ -137,7 +137,7 @@ func (c *Conn) doCommand(ctx context.Context, command string, args ...interface{ } // resultToVar converts redis operation result to gvar.Var. -func (c *Conn) resultToVar(result interface{}, err error) (*gvar.Var, error) { +func (c *Conn) resultToVar(result any, err error) (*gvar.Var, error) { if err == redis.Nil { err = nil } @@ -146,7 +146,7 @@ func (c *Conn) resultToVar(result interface{}, err error) (*gvar.Var, error) { case []byte: return gvar.New(string(v)), err - case []interface{}: + case []any: return gvar.New(gconv.Strings(v)), err case *redis.Message: @@ -196,7 +196,7 @@ func (c *Conn) Close(ctx context.Context) (err error) { // // https://redis.io/commands/subscribe/ func (c *Conn) Subscribe(ctx context.Context, channel string, channels ...string) ([]*gredis.Subscription, error) { - args := append([]interface{}{channel}, gconv.Interfaces(channels)...) + args := append([]any{channel}, gconv.Interfaces(channels)...) _, err := c.Do(ctx, "Subscribe", args...) if err != nil { return nil, err @@ -223,7 +223,7 @@ func (c *Conn) Subscribe(ctx context.Context, channel string, channels ...string // // https://redis.io/commands/psubscribe/ func (c *Conn) PSubscribe(ctx context.Context, pattern string, patterns ...string) ([]*gredis.Subscription, error) { - args := append([]interface{}{pattern}, gconv.Interfaces(patterns)...) + args := append([]any{pattern}, gconv.Interfaces(patterns)...) _, err := c.Do(ctx, "PSubscribe", args...) if err != nil { return nil, err diff --git a/contrib/nosql/redis/redis_func.go b/contrib/nosql/redis/redis_func.go index e9a86dd707b..acf8727c39a 100644 --- a/contrib/nosql/redis/redis_func.go +++ b/contrib/nosql/redis/redis_func.go @@ -12,13 +12,13 @@ import ( "github.com/gogf/gf/v2/os/gstructs" ) -func mustMergeOptionToArgs(args []interface{}, option interface{}) []interface{} { +func mustMergeOptionToArgs(args []any, option any) []any { if option == nil { return args } var ( err error - optionArgs []interface{} + optionArgs []any ) optionArgs, err = convertOptionToArgs(option) if err != nil { @@ -27,13 +27,13 @@ func mustMergeOptionToArgs(args []interface{}, option interface{}) []interface{} return append(args, optionArgs...) } -func convertOptionToArgs(option interface{}) ([]interface{}, error) { +func convertOptionToArgs(option any) ([]any, error) { if option == nil { return nil, nil } var ( err error - args = make([]interface{}, 0) + args = make([]any, 0) fields []gstructs.Field subFields []gstructs.Field ) @@ -74,7 +74,7 @@ func convertOptionToArgs(option interface{}) ([]interface{}, error) { // See TTLOption default: fieldValue := field.Value.Interface() - if field.Value.Kind() == reflect.Ptr { + if field.Value.Kind() == reflect.Pointer { if field.Value.IsNil() { continue } diff --git a/contrib/nosql/redis/redis_group_generic.go b/contrib/nosql/redis/redis_group_generic.go index 1765b2bb018..b0e9e312749 100644 --- a/contrib/nosql/redis/redis_group_generic.go +++ b/contrib/nosql/redis/redis_group_generic.go @@ -41,12 +41,12 @@ func (r *Redis) GroupGeneric() gredis.IGroupGeneric { // // https://redis.io/commands/copy/ func (r GroupGeneric) Copy(ctx context.Context, source, destination string, option ...gredis.CopyOption) (int64, error) { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0] } v, err := r.Operation.Do(ctx, "Copy", mustMergeOptionToArgs( - []interface{}{source, destination}, usedOption, + []any{source, destination}, usedOption, )...) return v.Int64(), err } @@ -179,13 +179,13 @@ func (r GroupGeneric) Keys(ctx context.Context, pattern string) ([]string, error // // https://redis.io/commands/scan/ func (r GroupGeneric) Scan(ctx context.Context, cursor uint64, option ...gredis.ScanOption) (uint64, []string, error) { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0].ToUsedOption() } v, err := r.Operation.Do(ctx, "Scan", mustMergeOptionToArgs( - []interface{}{cursor}, usedOption, + []any{cursor}, usedOption, )...) if err != nil { return 0, nil, err @@ -231,12 +231,12 @@ func (r GroupGeneric) FlushAll(ctx context.Context, option ...gredis.FlushOp) er // // https://redis.io/commands/expire/ func (r GroupGeneric) Expire(ctx context.Context, key string, seconds int64, option ...gredis.ExpireOption) (int64, error) { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0] } v, err := r.Operation.Do(ctx, "Expire", mustMergeOptionToArgs( - []interface{}{key, seconds}, usedOption, + []any{key, seconds}, usedOption, )...) return v.Int64(), err } @@ -252,12 +252,12 @@ func (r GroupGeneric) Expire(ctx context.Context, key string, seconds int64, opt // // https://redis.io/commands/expireat/ func (r GroupGeneric) ExpireAt(ctx context.Context, key string, time time.Time, option ...gredis.ExpireOption) (int64, error) { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0] } v, err := r.Operation.Do(ctx, "ExpireAt", mustMergeOptionToArgs( - []interface{}{key, gtime.New(time).Timestamp()}, usedOption, + []any{key, gtime.New(time).Timestamp()}, usedOption, )...) return v.Int64(), err } @@ -316,12 +316,12 @@ func (r GroupGeneric) Persist(ctx context.Context, key string) (int64, error) { // // https://redis.io/commands/pexpire/ func (r GroupGeneric) PExpire(ctx context.Context, key string, milliseconds int64, option ...gredis.ExpireOption) (int64, error) { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0] } v, err := r.Operation.Do(ctx, "PExpire", mustMergeOptionToArgs( - []interface{}{key, milliseconds}, usedOption, + []any{key, milliseconds}, usedOption, )...) return v.Int64(), err } @@ -331,12 +331,12 @@ func (r GroupGeneric) PExpire(ctx context.Context, key string, milliseconds int6 // // https://redis.io/commands/pexpireat/ func (r GroupGeneric) PExpireAt(ctx context.Context, key string, time time.Time, option ...gredis.ExpireOption) (int64, error) { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0] } v, err := r.Operation.Do(ctx, "PExpireAt", mustMergeOptionToArgs( - []interface{}{key, gtime.New(time).TimestampMilli()}, usedOption, + []any{key, gtime.New(time).TimestampMilli()}, usedOption, )...) return v.Int64(), err } diff --git a/contrib/nosql/redis/redis_group_hash.go b/contrib/nosql/redis/redis_group_hash.go index 75b3147430c..6306eebace8 100644 --- a/contrib/nosql/redis/redis_group_hash.go +++ b/contrib/nosql/redis/redis_group_hash.go @@ -33,8 +33,8 @@ func (r *Redis) GroupHash() gredis.IGroupHash { // It returns the number of fields that were added. // // https://redis.io/commands/hset/ -func (r GroupHash) HSet(ctx context.Context, key string, fields map[string]interface{}) (int64, error) { - var s = []interface{}{key} +func (r GroupHash) HSet(ctx context.Context, key string, fields map[string]any) (int64, error) { + var s = []any{key} for k, v := range fields { s = append(s, k, v) } @@ -51,7 +51,7 @@ func (r GroupHash) HSet(ctx context.Context, key string, fields map[string]inter // - 0 if field already exists in the hash and no operation was performed. // // https://redis.io/commands/hsetnx/ -func (r GroupHash) HSetNX(ctx context.Context, key, field string, value interface{}) (int64, error) { +func (r GroupHash) HSetNX(ctx context.Context, key, field string, value any) (int64, error) { v, err := r.Operation.Do(ctx, "HSetNX", key, field, value) return v.Int64(), err } @@ -98,7 +98,7 @@ func (r GroupHash) HExists(ctx context.Context, key, field string) (int64, error // // https://redis.io/commands/hdel/ func (r GroupHash) HDel(ctx context.Context, key string, fields ...string) (int64, error) { - v, err := r.Operation.Do(ctx, "HDel", append([]interface{}{key}, gconv.Interfaces(fields)...)...) + v, err := r.Operation.Do(ctx, "HDel", append([]any{key}, gconv.Interfaces(fields)...)...) return v.Int64(), err } @@ -147,8 +147,8 @@ func (r GroupHash) HIncrByFloat(ctx context.Context, key, field string, incremen // If key does not exist, a new key holding a hash is created. // // https://redis.io/commands/hmset/ -func (r GroupHash) HMSet(ctx context.Context, key string, fields map[string]interface{}) error { - var s = []interface{}{key} +func (r GroupHash) HMSet(ctx context.Context, key string, fields map[string]any) error { + var s = []any{key} for k, v := range fields { s = append(s, k, v) } @@ -163,7 +163,7 @@ func (r GroupHash) HMSet(ctx context.Context, key string, fields map[string]inte // // https://redis.io/commands/hmget/ func (r GroupHash) HMGet(ctx context.Context, key string, fields ...string) (gvar.Vars, error) { - v, err := r.Operation.Do(ctx, "HMGet", append([]interface{}{key}, gconv.Interfaces(fields)...)...) + v, err := r.Operation.Do(ctx, "HMGet", append([]any{key}, gconv.Interfaces(fields)...)...) return v.Vars(), err } diff --git a/contrib/nosql/redis/redis_group_list.go b/contrib/nosql/redis/redis_group_list.go index 6767e723fbe..e98ea409c6d 100644 --- a/contrib/nosql/redis/redis_group_list.go +++ b/contrib/nosql/redis/redis_group_list.go @@ -34,8 +34,8 @@ func (r *Redis) GroupList() gredis.IGroupList { // It returns the length of the list after the push operations. // // https://redis.io/commands/lpush/ -func (r GroupList) LPush(ctx context.Context, key string, values ...interface{}) (int64, error) { - v, err := r.Operation.Do(ctx, "LPush", append([]interface{}{key}, values...)...) +func (r GroupList) LPush(ctx context.Context, key string, values ...any) (int64, error) { + v, err := r.Operation.Do(ctx, "LPush", append([]any{key}, values...)...) return v.Int64(), err } @@ -47,8 +47,8 @@ func (r GroupList) LPush(ctx context.Context, key string, values ...interface{}) // It returns the length of the list after the push operations. // // https://redis.io/commands/lpushx -func (r GroupList) LPushX(ctx context.Context, key string, element interface{}, elements ...interface{}) (int64, error) { - v, err := r.Operation.Do(ctx, "LPushX", append([]interface{}{key, element}, elements...)...) +func (r GroupList) LPushX(ctx context.Context, key string, element any, elements ...any) (int64, error) { + v, err := r.Operation.Do(ctx, "LPushX", append([]any{key, element}, elements...)...) return v.Int64(), err } @@ -66,8 +66,8 @@ func (r GroupList) LPushX(ctx context.Context, key string, element interface{}, // It returns the length of the list after the push operation. // // https://redis.io/commands/rpush -func (r GroupList) RPush(ctx context.Context, key string, values ...interface{}) (int64, error) { - v, err := r.Operation.Do(ctx, "RPush", append([]interface{}{key}, values...)...) +func (r GroupList) RPush(ctx context.Context, key string, values ...any) (int64, error) { + v, err := r.Operation.Do(ctx, "RPush", append([]any{key}, values...)...) return v.Int64(), err } @@ -80,7 +80,7 @@ func (r GroupList) RPush(ctx context.Context, key string, values ...interface{}) // It returns the length of the list after the push operation. // // https://redis.io/commands/rpushx -func (r GroupList) RPushX(ctx context.Context, key string, value interface{}) (int64, error) { +func (r GroupList) RPushX(ctx context.Context, key string, value any) (int64, error) { v, err := r.Operation.Do(ctx, "RPushX", key, value) return v.Int64(), err } @@ -136,7 +136,7 @@ func (r GroupList) RPop(ctx context.Context, key string, count ...int) (*gvar.Va // It returns the number of removed elements. // // https://redis.io/commands/lrem/ -func (r GroupList) LRem(ctx context.Context, key string, count int64, value interface{}) (int64, error) { +func (r GroupList) LRem(ctx context.Context, key string, count int64, value any) (int64, error) { v, err := r.Operation.Do(ctx, "LRem", key, count, value) return v.Int64(), err } @@ -173,7 +173,7 @@ func (r GroupList) LIndex(ctx context.Context, key string, index int64) (*gvar.V // It returns the length of the list after the insert operation, or -1 when the value pivot was not found. // // https://redis.io/commands/linsert/ -func (r GroupList) LInsert(ctx context.Context, key string, op gredis.LInsertOp, pivot, value interface{}) (int64, error) { +func (r GroupList) LInsert(ctx context.Context, key string, op gredis.LInsertOp, pivot, value any) (int64, error) { v, err := r.Operation.Do(ctx, "LInsert", key, string(op), pivot, value) return v.Int64(), err } @@ -183,7 +183,7 @@ func (r GroupList) LInsert(ctx context.Context, key string, op gredis.LInsertOp, // An error is returned for out of range indexes. // // https://redis.io/commands/lset/ -func (r GroupList) LSet(ctx context.Context, key string, index int64, value interface{}) (*gvar.Var, error) { +func (r GroupList) LSet(ctx context.Context, key string, index int64, value any) (*gvar.Var, error) { return r.Operation.Do(ctx, "LSet", key, index, value) } diff --git a/contrib/nosql/redis/redis_group_pubsub.go b/contrib/nosql/redis/redis_group_pubsub.go index 1badd05e179..d623c182f27 100644 --- a/contrib/nosql/redis/redis_group_pubsub.go +++ b/contrib/nosql/redis/redis_group_pubsub.go @@ -35,7 +35,7 @@ func (r *Redis) GroupPubSub() gredis.IGroupPubSub { // are included in the count. // // https://redis.io/commands/publish/ -func (r GroupPubSub) Publish(ctx context.Context, channel string, message interface{}) (int64, error) { +func (r GroupPubSub) Publish(ctx context.Context, channel string, message any) (int64, error) { v, err := r.Operation.Do(ctx, "Publish", channel, message) return v.Int64(), err } diff --git a/contrib/nosql/redis/redis_group_script.go b/contrib/nosql/redis/redis_group_script.go index 3f1a6ef77a7..e7cd81336b1 100644 --- a/contrib/nosql/redis/redis_group_script.go +++ b/contrib/nosql/redis/redis_group_script.go @@ -29,8 +29,8 @@ func (r *Redis) GroupScript() gredis.IGroupScript { // Eval invokes the execution of a server-side Lua script. // // https://redis.io/commands/eval/ -func (r GroupScript) Eval(ctx context.Context, script string, numKeys int64, keys []string, args []interface{}) (*gvar.Var, error) { - var s = []interface{}{script, numKeys} +func (r GroupScript) Eval(ctx context.Context, script string, numKeys int64, keys []string, args []any) (*gvar.Var, error) { + var s = []any{script, numKeys} s = append(s, gconv.Interfaces(keys)...) s = append(s, args...) v, err := r.Operation.Do(ctx, "Eval", s...) @@ -43,8 +43,8 @@ func (r GroupScript) Eval(ctx context.Context, script string, numKeys int64, key // The command is otherwise identical to EVAL. // // https://redis.io/commands/evalsha/ -func (r GroupScript) EvalSha(ctx context.Context, sha1 string, numKeys int64, keys []string, args []interface{}) (*gvar.Var, error) { - var s = []interface{}{sha1, numKeys} +func (r GroupScript) EvalSha(ctx context.Context, sha1 string, numKeys int64, keys []string, args []any) (*gvar.Var, error) { + var s = []any{sha1, numKeys} s = append(s, gconv.Interfaces(keys)...) s = append(s, args...) v, err := r.Operation.Do(ctx, "EvalSha", s...) @@ -70,8 +70,8 @@ func (r GroupScript) ScriptLoad(ctx context.Context, script string) (string, err // https://redis.io/commands/script-exists/ func (r GroupScript) ScriptExists(ctx context.Context, sha1 string, sha1s ...string) (map[string]bool, error) { var ( - s []interface{} - sha1Array = append([]interface{}{sha1}, gconv.Interfaces(sha1s)...) + s []any + sha1Array = append([]any{sha1}, gconv.Interfaces(sha1s)...) ) s = append(s, "Exists") s = append(s, sha1Array...) @@ -93,14 +93,14 @@ func (r GroupScript) ScriptExists(ctx context.Context, sha1 string, sha1s ...str // // https://redis.io/commands/script-flush/ func (r GroupScript) ScriptFlush(ctx context.Context, option ...gredis.ScriptFlushOption) error { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0] } - var s []interface{} + var s []any s = append(s, "Flush") s = append(s, mustMergeOptionToArgs( - []interface{}{}, usedOption, + []any{}, usedOption, )...) _, err := r.Operation.Do(ctx, "Script", s...) return err diff --git a/contrib/nosql/redis/redis_group_set.go b/contrib/nosql/redis/redis_group_set.go index 631f2d9ff07..94eea67a62c 100644 --- a/contrib/nosql/redis/redis_group_set.go +++ b/contrib/nosql/redis/redis_group_set.go @@ -36,8 +36,8 @@ func (r *Redis) GroupSet() gredis.IGroupSet { // not including all the elements already present in the set. // // https://redis.io/commands/sadd/ -func (r GroupSet) SAdd(ctx context.Context, key string, member interface{}, members ...interface{}) (int64, error) { - var s = []interface{}{key} +func (r GroupSet) SAdd(ctx context.Context, key string, member any, members ...any) (int64, error) { + var s = []any{key} s = append(s, member) s = append(s, members...) v, err := r.Operation.Do(ctx, "SAdd", s...) @@ -51,7 +51,7 @@ func (r GroupSet) SAdd(ctx context.Context, key string, member interface{}, memb // - 0 if the element is not a member of the set, or if key does not exist. // // https://redis.io/commands/sismember/ -func (r GroupSet) SIsMember(ctx context.Context, key string, member interface{}) (int64, error) { +func (r GroupSet) SIsMember(ctx context.Context, key string, member any) (int64, error) { v, err := r.Operation.Do(ctx, "SIsMember", key, member) return v.Int64(), err } @@ -71,7 +71,7 @@ func (r GroupSet) SIsMember(ctx context.Context, key string, member interface{}) // // https://redis.io/commands/spop/ func (r GroupSet) SPop(ctx context.Context, key string, count ...int) (*gvar.Var, error) { - var s = []interface{}{key} + var s = []any{key} s = append(s, gconv.Interfaces(count)...) v, err := r.Operation.Do(ctx, "SPop", s...) return v, err @@ -93,7 +93,7 @@ func (r GroupSet) SPop(ctx context.Context, key string, count ...int) (*gvar.Var // // https://redis.io/commands/srandmember/ func (r GroupSet) SRandMember(ctx context.Context, key string, count ...int) (*gvar.Var, error) { - var s = []interface{}{key} + var s = []any{key} s = append(s, gconv.Interfaces(count)...) v, err := r.Operation.Do(ctx, "SRandMember", s...) return v, err @@ -108,8 +108,8 @@ func (r GroupSet) SRandMember(ctx context.Context, key string, count ...int) (*g // It returns the number of members that were removed from the set, not including non existing members. // // https://redis.io/commands/srem/ -func (r GroupSet) SRem(ctx context.Context, key string, member interface{}, members ...interface{}) (int64, error) { - var s = []interface{}{key} +func (r GroupSet) SRem(ctx context.Context, key string, member any, members ...any) (int64, error) { + var s = []any{key} s = append(s, member) s = append(s, members...) v, err := r.Operation.Do(ctx, "SRem", s...) @@ -130,7 +130,7 @@ func (r GroupSet) SRem(ctx context.Context, key string, member interface{}, memb // - 0 if the element is not a member of source and no operation was performed. // // https://redis.io/commands/smove/ -func (r GroupSet) SMove(ctx context.Context, source, destination string, member interface{}) (int64, error) { +func (r GroupSet) SMove(ctx context.Context, source, destination string, member any) (int64, error) { v, err := r.Operation.Do(ctx, "SMove", source, destination, member) return v.Int64(), err } @@ -164,8 +164,8 @@ func (r GroupSet) SMembers(ctx context.Context, key string) (gvar.Vars, error) { // It returns list representing the membership of the given elements, in the same order as they are requested. // // https://redis.io/commands/smismember/ -func (r GroupSet) SMIsMember(ctx context.Context, key, member interface{}, members ...interface{}) ([]int, error) { - var s = []interface{}{key, member} +func (r GroupSet) SMIsMember(ctx context.Context, key, member any, members ...any) ([]int, error) { + var s = []any{key, member} s = append(s, members...) v, err := r.Operation.Do(ctx, "SMIsMember", s...) return v.Ints(), err @@ -177,7 +177,7 @@ func (r GroupSet) SMIsMember(ctx context.Context, key, member interface{}, membe // // https://redis.io/commands/sinter/ func (r GroupSet) SInter(ctx context.Context, key string, keys ...string) (gvar.Vars, error) { - var s = []interface{}{key} + var s = []any{key} s = append(s, gconv.Interfaces(keys)...) v, err := r.Operation.Do(ctx, "SInter", s...) return v.Vars(), err @@ -192,7 +192,7 @@ func (r GroupSet) SInter(ctx context.Context, key string, keys ...string) (gvar. // // https://redis.io/commands/sinterstore/ func (r GroupSet) SInterStore(ctx context.Context, destination string, key string, keys ...string) (int64, error) { - var s = []interface{}{destination, key} + var s = []any{destination, key} s = append(s, gconv.Interfaces(keys)...) v, err := r.Operation.Do(ctx, "SInterStore", s...) return v.Int64(), err @@ -204,7 +204,7 @@ func (r GroupSet) SInterStore(ctx context.Context, destination string, key strin // // https://redis.io/commands/sunion/ func (r GroupSet) SUnion(ctx context.Context, key string, keys ...string) (gvar.Vars, error) { - var s = []interface{}{key} + var s = []any{key} s = append(s, gconv.Interfaces(keys)...) v, err := r.Operation.Do(ctx, "SUnion", s...) return v.Vars(), err @@ -218,7 +218,7 @@ func (r GroupSet) SUnion(ctx context.Context, key string, keys ...string) (gvar. // // https://redis.io/commands/sunionstore/ func (r GroupSet) SUnionStore(ctx context.Context, destination, key string, keys ...string) (int64, error) { - var s = []interface{}{destination, key} + var s = []any{destination, key} s = append(s, gconv.Interfaces(keys)...) v, err := r.Operation.Do(ctx, "SUnionStore", s...) return v.Int64(), err @@ -231,7 +231,7 @@ func (r GroupSet) SUnionStore(ctx context.Context, destination, key string, keys // // https://redis.io/commands/sdiff/ func (r GroupSet) SDiff(ctx context.Context, key string, keys ...string) (gvar.Vars, error) { - var s = []interface{}{key} + var s = []any{key} s = append(s, gconv.Interfaces(keys)...) v, err := r.Operation.Do(ctx, "SDiff", s...) return v.Vars(), err @@ -245,7 +245,7 @@ func (r GroupSet) SDiff(ctx context.Context, key string, keys ...string) (gvar.V // // https://redis.io/commands/sdiffstore/ func (r GroupSet) SDiffStore(ctx context.Context, destination string, key string, keys ...string) (int64, error) { - var s = []interface{}{destination, key} + var s = []any{destination, key} s = append(s, gconv.Interfaces(keys)...) v, err := r.Operation.Do(ctx, "SDiffStore", s...) return v.Int64(), err diff --git a/contrib/nosql/redis/redis_group_sorted_set.go b/contrib/nosql/redis/redis_group_sorted_set.go index 667118a231f..5cf634690f9 100644 --- a/contrib/nosql/redis/redis_group_sorted_set.go +++ b/contrib/nosql/redis/redis_group_sorted_set.go @@ -49,7 +49,7 @@ func (r GroupSortedSet) ZAdd( ctx context.Context, key string, option *gredis.ZAddOption, member gredis.ZAddMember, members ...gredis.ZAddMember, ) (*gvar.Var, error) { s := mustMergeOptionToArgs( - []interface{}{key}, option, + []any{key}, option, ) s = append(s, member.Score, member.Member) for _, item := range members { @@ -66,7 +66,7 @@ func (r GroupSortedSet) ZAdd( // It returns the score of member (a double precision floating point number), represented as string. // // https://redis.io/commands/zscore/ -func (r GroupSortedSet) ZScore(ctx context.Context, key string, member interface{}) (float64, error) { +func (r GroupSortedSet) ZScore(ctx context.Context, key string, member any) (float64, error) { v, err := r.Operation.Do(ctx, "ZScore", key, member) return v.Float64(), err } @@ -83,7 +83,7 @@ func (r GroupSortedSet) ZScore(ctx context.Context, key string, member interface // It returns the new score of member (a double precision floating point number). // // https://redis.io/commands/zincrby/ -func (r GroupSortedSet) ZIncrBy(ctx context.Context, key string, increment float64, member interface{}) (float64, error) { +func (r GroupSortedSet) ZIncrBy(ctx context.Context, key string, increment float64, member any) (float64, error) { v, err := r.Operation.Do(ctx, "ZIncrBy", key, increment, member) return v.Float64(), err } @@ -120,12 +120,12 @@ func (r GroupSortedSet) ZCount(ctx context.Context, key string, min, max string) // // https://redis.io/commands/zrange/ func (r GroupSortedSet) ZRange(ctx context.Context, key string, start, stop int64, option ...gredis.ZRangeOption) (gvar.Vars, error) { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0] } v, err := r.Operation.Do(ctx, "ZRange", mustMergeOptionToArgs( - []interface{}{key, start, stop}, usedOption, + []any{key, start, stop}, usedOption, )...) return v.Vars(), err } @@ -140,12 +140,12 @@ func (r GroupSortedSet) ZRange(ctx context.Context, key string, start, stop int6 // // https://redis.io/commands/zrevrange/ func (r GroupSortedSet) ZRevRange(ctx context.Context, key string, start, stop int64, option ...gredis.ZRevRangeOption) (*gvar.Var, error) { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0] } return r.Operation.Do(ctx, "ZRevRange", mustMergeOptionToArgs( - []interface{}{key, start, stop}, usedOption, + []any{key, start, stop}, usedOption, )...) } @@ -159,7 +159,7 @@ func (r GroupSortedSet) ZRevRange(ctx context.Context, key string, start, stop i // - If member does not exist in the sorted set or key does not exist, Bulk string reply: nil. // // https://redis.io/commands/zrank/ -func (r GroupSortedSet) ZRank(ctx context.Context, key string, member interface{}) (int64, error) { +func (r GroupSortedSet) ZRank(ctx context.Context, key string, member any) (int64, error) { v, err := r.Operation.Do(ctx, "ZRank", key, member) return v.Int64(), err } @@ -174,7 +174,7 @@ func (r GroupSortedSet) ZRank(ctx context.Context, key string, member interface{ // - If member does not exist in the sorted set or key does not exist, Bulk string reply: nil. // // https://redis.io/commands/zrevrank/ -func (r GroupSortedSet) ZRevRank(ctx context.Context, key string, member interface{}) (int64, error) { +func (r GroupSortedSet) ZRevRank(ctx context.Context, key string, member any) (int64, error) { v, err := r.Operation.Do(ctx, "ZRevRank", key, member) return v.Int64(), err } @@ -187,8 +187,8 @@ func (r GroupSortedSet) ZRevRank(ctx context.Context, key string, member interfa // It returns the number of members removed from the sorted set, not including non existing members. // // https://redis.io/commands/zrem/ -func (r GroupSortedSet) ZRem(ctx context.Context, key string, member interface{}, members ...interface{}) (int64, error) { - var s = []interface{}{key} +func (r GroupSortedSet) ZRem(ctx context.Context, key string, member any, members ...any) (int64, error) { + var s = []any{key} s = append(s, member) s = append(s, members...) v, err := r.Operation.Do(ctx, "ZRem", s...) diff --git a/contrib/nosql/redis/redis_group_string.go b/contrib/nosql/redis/redis_group_string.go index 1cac4ad054e..c16ba24506b 100644 --- a/contrib/nosql/redis/redis_group_string.go +++ b/contrib/nosql/redis/redis_group_string.go @@ -31,13 +31,13 @@ func (r *Redis) GroupString() gredis.IGroupString { // Any previous time to live associated with the key is discarded on successful SET operation. // // https://redis.io/commands/set/ -func (r GroupString) Set(ctx context.Context, key string, value interface{}, option ...gredis.SetOption) (*gvar.Var, error) { - var usedOption interface{} +func (r GroupString) Set(ctx context.Context, key string, value any, option ...gredis.SetOption) (*gvar.Var, error) { + var usedOption any if len(option) > 0 { usedOption = option[0] } return r.Operation.Do(ctx, "Set", mustMergeOptionToArgs( - []interface{}{key, value}, usedOption, + []any{key, value}, usedOption, )...) } @@ -51,7 +51,7 @@ func (r GroupString) Set(ctx context.Context, key string, value interface{}, opt // false: if no key was set (at least one key already existed). // // https://redis.io/commands/setnx/ -func (r GroupString) SetNX(ctx context.Context, key string, value interface{}) (bool, error) { +func (r GroupString) SetNX(ctx context.Context, key string, value any) (bool, error) { v, err := r.Operation.Do(ctx, "SetNX", key, value) return v.Bool(), err } @@ -69,7 +69,7 @@ func (r GroupString) SetNX(ctx context.Context, key string, value interface{}) ( // An error is returned when seconds invalid. // // https://redis.io/commands/setex/ -func (r GroupString) SetEX(ctx context.Context, key string, value interface{}, ttlInSeconds int64) error { +func (r GroupString) SetEX(ctx context.Context, key string, value any, ttlInSeconds int64) error { _, err := r.Operation.Do(ctx, "SetEX", key, ttlInSeconds, value) return err } @@ -95,12 +95,12 @@ func (r GroupString) GetDel(ctx context.Context, key string) (*gvar.Var, error) // // https://redis.io/commands/getex/ func (r GroupString) GetEX(ctx context.Context, key string, option ...gredis.GetEXOption) (*gvar.Var, error) { - var usedOption interface{} + var usedOption any if len(option) > 0 { usedOption = option[0] } return r.Operation.Do(ctx, "GetEX", mustMergeOptionToArgs( - []interface{}{key}, usedOption, + []any{key}, usedOption, )...) } @@ -109,7 +109,7 @@ func (r GroupString) GetEX(ctx context.Context, key string, option ...gredis.Get // the key is discarded on successful SET operation. // // https://redis.io/commands/getset/ -func (r GroupString) GetSet(ctx context.Context, key string, value interface{}) (*gvar.Var, error) { +func (r GroupString) GetSet(ctx context.Context, key string, value any) (*gvar.Var, error) { return r.Operation.Do(ctx, "GetSet", key, value) } @@ -214,8 +214,8 @@ func (r GroupString) DecrBy(ctx context.Context, key string, decrement int64) (i // were updated while others are unchanged. // // https://redis.io/commands/mset/ -func (r GroupString) MSet(ctx context.Context, keyValueMap map[string]interface{}) error { - var args []interface{} +func (r GroupString) MSet(ctx context.Context, keyValueMap map[string]any) error { + var args []any for k, v := range keyValueMap { args = append(args, k, v) } @@ -228,8 +228,8 @@ func (r GroupString) MSet(ctx context.Context, keyValueMap map[string]interface{ // It returns: // true: if the all the keys were set. // false: if no key was set (at least one key already existed). -func (r GroupString) MSetNX(ctx context.Context, keyValueMap map[string]interface{}) (bool, error) { - var args []interface{} +func (r GroupString) MSetNX(ctx context.Context, keyValueMap map[string]any) (bool, error) { + var args []any for k, v := range keyValueMap { args = append(args, k, v) } diff --git a/contrib/nosql/redis/redis_operation.go b/contrib/nosql/redis/redis_operation.go index 191ca866f6b..3e7ba762600 100644 --- a/contrib/nosql/redis/redis_operation.go +++ b/contrib/nosql/redis/redis_operation.go @@ -16,7 +16,7 @@ import ( // Do send a command to the server and returns the received reply. // It uses json.Marshal for struct/slice/map type values before committing them to redis. -func (r *Redis) Do(ctx context.Context, command string, args ...interface{}) (*gvar.Var, error) { +func (r *Redis) Do(ctx context.Context, command string, args ...any) (*gvar.Var, error) { conn, err := r.Conn(ctx) if err != nil { return nil, err diff --git a/contrib/nosql/redis/redis_z_func_test.go b/contrib/nosql/redis/redis_z_func_test.go index cd860a54f45..8fc4224244a 100644 --- a/contrib/nosql/redis/redis_z_func_test.go +++ b/contrib/nosql/redis/redis_z_func_test.go @@ -16,15 +16,15 @@ import ( func Test_mustMergeOptionToArgs(t *testing.T) { gtest.C(t, func(t *gtest.T) { - var args []interface{} + var args []any newArgs := mustMergeOptionToArgs(args, gredis.SetOption{ NX: true, Get: true, }) - t.Assert(newArgs, []interface{}{"NX", "Get"}) + t.Assert(newArgs, []any{"NX", "Get"}) }) gtest.C(t, func(t *gtest.T) { - var args []interface{} + var args []any newArgs := mustMergeOptionToArgs(args, gredis.SetOption{ NX: true, Get: true, @@ -32,6 +32,6 @@ func Test_mustMergeOptionToArgs(t *testing.T) { EX: gconv.PtrInt64(60), }, }) - t.Assert(newArgs, []interface{}{"EX", 60, "NX", "Get"}) + t.Assert(newArgs, []any{"EX", 60, "NX", "Get"}) }) } diff --git a/contrib/nosql/redis/redis_z_group_generic_test.go b/contrib/nosql/redis/redis_z_group_generic_test.go index b4bc4bce15e..9c287352085 100644 --- a/contrib/nosql/redis/redis_z_group_generic_test.go +++ b/contrib/nosql/redis/redis_z_group_generic_test.go @@ -239,7 +239,7 @@ func Test_GroupGeneric_Keys(t *testing.T) { gtest.C(t, func(t *gtest.T) { defer redis.FlushDB(ctx) - err := redis.GroupString().MSet(ctx, map[string]interface{}{ + err := redis.GroupString().MSet(ctx, map[string]any{ "firstname": "Jack", "lastname": "Stuntman", "age": 35, @@ -261,7 +261,7 @@ func Test_GroupGeneric_Scan(t *testing.T) { gtest.C(t, func(t *gtest.T) { defer redis.FlushDB(ctx) - err := redis.GroupString().MSet(ctx, map[string]interface{}{ + err := redis.GroupString().MSet(ctx, map[string]any{ "firstname": "Jack", "lastname": "Stuntman", "age": 35, diff --git a/contrib/nosql/redis/redis_z_group_hash_test.go b/contrib/nosql/redis/redis_z_group_hash_test.go index b365c537adf..137a071f4b5 100644 --- a/contrib/nosql/redis/redis_z_group_hash_test.go +++ b/contrib/nosql/redis/redis_z_group_hash_test.go @@ -19,7 +19,7 @@ func Test_GroupHash_HSet(t *testing.T) { key = "myhash" field1 = "field1" field1Value = "Hello" - fields = map[string]interface{}{ + fields = map[string]any{ field1: field1Value, } ) @@ -59,7 +59,7 @@ func Test_GroupHash_HStrLen(t *testing.T) { field1Value = "Hello" field2 = "field2" field2Value = "Hello World" - fields = map[string]interface{}{ + fields = map[string]any{ field1: field1Value, } ) @@ -87,7 +87,7 @@ func Test_GroupHash_HExists(t *testing.T) { key = "myhash" field1 = "field1" field1Value = "Hello" - fields = map[string]interface{}{ + fields = map[string]any{ field1: field1Value, } ) @@ -115,7 +115,7 @@ func Test_GroupHash_HDel(t *testing.T) { v2 = "v2" k3 = "k3" v3 = "v3" - fields = map[string]interface{}{ + fields = map[string]any{ k1: v1, k2: v2, k3: v3, @@ -145,7 +145,7 @@ func Test_GroupHash_HLen(t *testing.T) { key = "myhash" field1 = "field1" field1Value = "Hello" - fields = map[string]interface{}{ + fields = map[string]any{ field1: field1Value, } ) @@ -156,7 +156,7 @@ func Test_GroupHash_HLen(t *testing.T) { t.AssertNil(err) t.Assert(1, fieldLen) - fields = map[string]interface{}{ + fields = map[string]any{ "k1": "v1", "k2": "v2", } @@ -173,7 +173,7 @@ func Test_GroupHash_HIncrBy(t *testing.T) { key = "myhash" field1 = "field1" field1Value = 1 - fields = map[string]interface{}{ + fields = map[string]any{ field1: field1Value, } ) @@ -201,7 +201,7 @@ func Test_GroupHash_HIncrByFloat(t *testing.T) { key = "myhash" field1 = "field1" field1Value = 10.50 - fields = map[string]interface{}{ + fields = map[string]any{ field1: field1Value, } ) @@ -231,7 +231,7 @@ func Test_GroupHash_HMSet(t *testing.T) { v1 = "v1" k2 = "k2" v2 = "v2" - fields = map[string]interface{}{ + fields = map[string]any{ k1: v1, k2: v2, } @@ -258,7 +258,7 @@ func Test_GroupHash_HMGet(t *testing.T) { v1 = "v1" k2 = "k2" v2 = "v2" - fields = map[string]interface{}{ + fields = map[string]any{ k1: v1, k2: v2, } @@ -279,7 +279,7 @@ func Test_GroupHash_HKeys(t *testing.T) { key = "myhash" k1 = "k1" v1 = "v1" - fields = map[string]interface{}{ + fields = map[string]any{ k1: v1, } ) @@ -299,7 +299,7 @@ func Test_GroupHash_HVals(t *testing.T) { key = "myhash" k1 = "k1" v1 = "v1" - fields = map[string]interface{}{ + fields = map[string]any{ k1: v1, } ) @@ -321,7 +321,7 @@ func Test_GroupHash_HGetAll(t *testing.T) { v1 = "v1" k2 = "k2" v2 = "v2" - fields = map[string]interface{}{ + fields = map[string]any{ k1: v1, k2: v2, } diff --git a/contrib/nosql/redis/redis_z_group_script_test.go b/contrib/nosql/redis/redis_z_group_script_test.go index 8e8fa5de960..79cfb56e446 100644 --- a/contrib/nosql/redis/redis_z_group_script_test.go +++ b/contrib/nosql/redis/redis_z_group_script_test.go @@ -22,7 +22,7 @@ func Test_GroupScript_Eval(t *testing.T) { script = `return ARGV[1]` numKeys int64 keys = []string{"hello"} - args = []interface{}(nil) + args = []any(nil) ) v, err := redis.GroupScript().Eval(ctx, script, numKeys, keys, args) t.AssertNil(err) @@ -37,7 +37,7 @@ func Test_GroupScript_EvalSha(t *testing.T) { script = gsha1.Encrypt(`return ARGV[1]`) numKeys int64 keys = []string{"hello"} - args = []interface{}(nil) + args = []any(nil) ) v, err := redis.GroupScript().EvalSha(ctx, script, numKeys, keys, args) t.AssertNil(err) diff --git a/contrib/nosql/redis/redis_z_group_set_test.go b/contrib/nosql/redis/redis_z_group_set_test.go index 94bf4060842..c43751bf12c 100644 --- a/contrib/nosql/redis/redis_z_group_set_test.go +++ b/contrib/nosql/redis/redis_z_group_set_test.go @@ -18,7 +18,7 @@ func Test_GroupSet_SAdd(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members = []interface{}{ + members = []any{ "v2", "v3", } @@ -34,7 +34,7 @@ func Test_GroupSet_SIsMember(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members = []interface{}{ + members = []any{ "v2", "v3", } @@ -54,7 +54,7 @@ func Test_GroupSet_SPop(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members = []interface{}{ + members = []any{ "v2", "v3", } @@ -74,7 +74,7 @@ func Test_GroupSet_SRandMember(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members = []interface{}{ + members = []any{ "v2", "v3", } @@ -94,7 +94,7 @@ func Test_GroupSet_SRem(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members = []interface{}{ + members = []any{ "v2", "v3", } @@ -114,12 +114,12 @@ func Test_GroupSet_SMove(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } k2 = guid.S() - members2 = []interface{}{ + members2 = []any{ "v5", "v6", } @@ -149,7 +149,7 @@ func Test_GroupSet_SCard(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } @@ -169,7 +169,7 @@ func Test_GroupSet_SMembers(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } @@ -189,7 +189,7 @@ func Test_GroupSet_SMIsMember(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } @@ -209,13 +209,13 @@ func Test_GroupSet_SInter(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } k2 = guid.S() - members2 = []interface{}{ + members2 = []any{ "v3", "v6", } @@ -240,13 +240,13 @@ func Test_GroupSet_SInterStore(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } k2 = guid.S() - members2 = []interface{}{ + members2 = []any{ "v4", "v6", } @@ -274,13 +274,13 @@ func Test_GroupSet_SUnion(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } k2 = guid.S() - members2 = []interface{}{ + members2 = []any{ "v5", "v6", } @@ -303,13 +303,13 @@ func Test_GroupSet_SUnionStore(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } k2 = guid.S() - members2 = []interface{}{ + members2 = []any{ "v5", "v6", } @@ -337,13 +337,13 @@ func Test_GroupSet_SDiff(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } k2 = guid.S() - members2 = []interface{}{ + members2 = []any{ "v5", "v6", } @@ -366,13 +366,13 @@ func Test_GroupSet_SDiffStore(t *testing.T) { defer redis.FlushDB(ctx) var ( k1 = guid.S() - members1 = []interface{}{ + members1 = []any{ "v2", "v3", } k2 = guid.S() - members2 = []interface{}{ + members2 = []any{ "v5", "v6", } diff --git a/contrib/nosql/redis/redis_z_group_sorted_set_test.go b/contrib/nosql/redis/redis_z_group_sorted_set_test.go index 5e53afc3152..cf2a6a0ebe4 100644 --- a/contrib/nosql/redis/redis_z_group_sorted_set_test.go +++ b/contrib/nosql/redis/redis_z_group_sorted_set_test.go @@ -379,7 +379,7 @@ func Test_GroupSortedSet_ZRange(t *testing.T) { // ret, err = redis.GroupSortedSet().ZRange(ctx, k, 0, -1, // gredis.ZRangeOption{WithScores: true}) // t.AssertNil(err) - // expectedScore := []interface{}{1, "one", 2, "two", 3, "three"} + // expectedScore := []any{1, "one", 2, "two", 3, "three"} // for i := 0; i < len(ret); i++ { // t.AssertEQ(ret[i].String(), expectedScore[i]) // } @@ -405,12 +405,12 @@ func Test_GroupSortedSet_ZRevRange(t *testing.T) { ret, err := redis.GroupSortedSet().ZRevRange(ctx, k, 0, -1) t.AssertNil(err) - expected := []interface{}{"three", "two", "one"} + expected := []any{"three", "two", "one"} t.AssertEQ(ret.Slice(), expected) ret, err = redis.GroupSortedSet().ZRevRange(ctx, k, 0, 1) t.AssertNil(err) - expected = []interface{}{"three", "two"} + expected = []any{"three", "two"} t.AssertEQ(ret.Slice(), expected) }) } diff --git a/contrib/nosql/redis/redis_z_group_string_test.go b/contrib/nosql/redis/redis_z_group_string_test.go index 99c9202add7..25a109981c6 100644 --- a/contrib/nosql/redis/redis_z_group_string_test.go +++ b/contrib/nosql/redis/redis_z_group_string_test.go @@ -353,7 +353,7 @@ func Test_GroupString_MSet(t *testing.T) { k2 = guid.S() v2 = guid.S() ) - err := redis.GroupString().MSet(ctx, map[string]interface{}{ + err := redis.GroupString().MSet(ctx, map[string]any{ k1: v1, k2: v2, }) @@ -378,13 +378,13 @@ func Test_GroupString_MSetNX(t *testing.T) { k2 = guid.S() v2 = guid.S() ) - ok, err := redis.GroupString().MSetNX(ctx, map[string]interface{}{ + ok, err := redis.GroupString().MSetNX(ctx, map[string]any{ k1: v1, }) t.AssertNil(err) t.Assert(ok, true) - ok, err = redis.GroupString().MSetNX(ctx, map[string]interface{}{ + ok, err = redis.GroupString().MSetNX(ctx, map[string]any{ k1: v1, k2: v2, }) @@ -410,7 +410,7 @@ func Test_GroupString_MGet(t *testing.T) { k2 = guid.S() v2 = guid.S() ) - err := redis.GroupString().MSet(ctx, map[string]interface{}{ + err := redis.GroupString().MSet(ctx, map[string]any{ k1: v1, k2: v2, }) diff --git a/contrib/nosql/redis/redis_z_unit_gcache_adapter_test.go b/contrib/nosql/redis/redis_z_unit_gcache_adapter_test.go index 73530963884..1c25fac1aee 100644 --- a/contrib/nosql/redis/redis_z_unit_gcache_adapter_test.go +++ b/contrib/nosql/redis/redis_z_unit_gcache_adapter_test.go @@ -242,7 +242,7 @@ func Test_AdapterRedis_SetIfNotExist(t *testing.T) { func Test_AdapterRedis_SetIfNotExistFunc(t *testing.T) { defer cacheRedis.Clear(ctx) gtest.C(t, func(t *gtest.T) { - exist, err := cacheRedis.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + exist, err := cacheRedis.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) t.AssertNil(err) @@ -253,7 +253,7 @@ func Test_AdapterRedis_SetIfNotExistFunc(t *testing.T) { func Test_AdapterRedis_SetIfNotExistFuncLock(t *testing.T) { defer cacheRedis.Clear(ctx) gtest.C(t, func(t *gtest.T) { - exist, err := cacheRedis.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + exist, err := cacheRedis.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) t.AssertNil(err) @@ -285,14 +285,14 @@ func Test_AdapterRedis_GetOrSetFunc(t *testing.T) { key = "key" value1 = "valueFunc" ) - v, err := cacheRedis.GetOrSetFunc(ctx, key, func(ctx context.Context) (value interface{}, err error) { + v, err := cacheRedis.GetOrSetFunc(ctx, key, func(ctx context.Context) (value any, err error) { value = value1 return }, 0) t.AssertNil(err) t.Assert(v, value1) - v, err = cacheRedis.GetOrSetFunc(ctx, key, func(ctx context.Context) (value interface{}, err error) { + v, err = cacheRedis.GetOrSetFunc(ctx, key, func(ctx context.Context) (value any, err error) { value = value1 return }, 0) @@ -304,7 +304,7 @@ func Test_AdapterRedis_GetOrSetFunc(t *testing.T) { var ( key = "key1" ) - v, err := cacheRedis.GetOrSetFunc(ctx, key, func(ctx context.Context) (interface{}, error) { + v, err := cacheRedis.GetOrSetFunc(ctx, key, func(ctx context.Context) (any, error) { return nil, nil }, 0) t.AssertNil(err) @@ -319,7 +319,7 @@ func Test_AdapterRedis_GetOrSetFuncLock(t *testing.T) { key = "key" value1 = "valueFuncLock" ) - v, err := cacheRedis.GetOrSetFuncLock(ctx, key, func(ctx context.Context) (value interface{}, err error) { + v, err := cacheRedis.GetOrSetFuncLock(ctx, key, func(ctx context.Context) (value any, err error) { value = value1 return }, time.Second*60) diff --git a/contrib/registry/consul/consul.go b/contrib/registry/consul/consul.go index 7968e2ee404..d73f3e0b62d 100644 --- a/contrib/registry/consul/consul.go +++ b/contrib/registry/consul/consul.go @@ -96,7 +96,7 @@ func New(opts ...Option) (gsvc.Registry, error) { func (r *Registry) Register(ctx context.Context, service gsvc.Service) (gsvc.Service, error) { metadata := service.GetMetadata() if metadata == nil { - metadata = make(map[string]interface{}) + metadata = make(map[string]any) } // Convert metadata to string map diff --git a/contrib/registry/consul/consul_discovery.go b/contrib/registry/consul/consul_discovery.go index 10fb237e581..d5cbbfe008b 100644 --- a/contrib/registry/consul/consul_discovery.go +++ b/contrib/registry/consul/consul_discovery.go @@ -35,7 +35,7 @@ func (r *Registry) Search(ctx context.Context, in gsvc.SearchInput) ([]gsvc.Serv } // Parse metadata - var metadata map[string]interface{} + var metadata map[string]any if metaStr, ok := service.Service.Meta["metadata"]; ok && metaStr != "" { if err = json.Unmarshal([]byte(metaStr), &metadata); err != nil { return nil, gerror.Wrap(err, "failed to unmarshal service metadata") diff --git a/contrib/registry/consul/consul_test.go b/contrib/registry/consul/consul_test.go index 912f9bd9a0f..46e95b7cbcf 100644 --- a/contrib/registry/consul/consul_test.go +++ b/contrib/registry/consul/consul_test.go @@ -27,7 +27,7 @@ func createTestService() gsvc.Service { return &gsvc.LocalService{ Name: testServiceName, Version: testServiceVersion, - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "region": "cn-east-1", "zone": "a", }, @@ -56,7 +56,7 @@ func Test_Registry_Basic(t *testing.T) { serviceWithInvalidMeta := &gsvc.LocalService{ Name: testServiceName, Version: testServiceVersion, - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "invalid": make(chan int), // This will fail JSON marshaling }, Endpoints: []gsvc.Endpoint{ @@ -105,7 +105,7 @@ func Test_Registry_Basic(t *testing.T) { servicesWithInvalidMeta, err := registry.Search(ctx, gsvc.SearchInput{ Name: testServiceName, Version: testServiceVersion, - Metadata: map[string]interface{}{"nonexistent": "value"}, + Metadata: map[string]any{"nonexistent": "value"}, }) t.AssertNil(err) t.Assert(len(servicesWithInvalidMeta), 0) @@ -213,7 +213,7 @@ func Test_Registry_MultipleServices(t *testing.T) { service1 := &gsvc.LocalService{ Name: testServiceName, Version: "1.0.0", - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "region": "us-east-1", }, Endpoints: []gsvc.Endpoint{ @@ -224,7 +224,7 @@ func Test_Registry_MultipleServices(t *testing.T) { service2 := &gsvc.LocalService{ Name: testServiceName, Version: "2.0.0", - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "region": "us-west-1", }, Endpoints: []gsvc.Endpoint{ @@ -272,7 +272,7 @@ func Test_Registry_MultipleServices(t *testing.T) { // Test search with metadata servicesEast, err := registry.Search(ctx, gsvc.SearchInput{ Name: testServiceName, - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "region": "us-east-1", }, }) @@ -328,7 +328,7 @@ func Test_Registry_MultipleServicesMetadataFiltering(t *testing.T) { service1 := &gsvc.LocalService{ Name: testServiceName, Version: "1.0.0", - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "region": "us-east-1", "env": "dev", }, @@ -340,7 +340,7 @@ func Test_Registry_MultipleServicesMetadataFiltering(t *testing.T) { service2 := &gsvc.LocalService{ Name: testServiceName, Version: "2.0.0", - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "region": "us-west-1", "env": "prod", }, @@ -364,7 +364,7 @@ func Test_Registry_MultipleServicesMetadataFiltering(t *testing.T) { // Test search with metadata filtering servicesDev, err := registry.Search(ctx, gsvc.SearchInput{ Name: testServiceName, - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "env": "dev", }, }) @@ -374,7 +374,7 @@ func Test_Registry_MultipleServicesMetadataFiltering(t *testing.T) { servicesProd, err := registry.Search(ctx, gsvc.SearchInput{ Name: testServiceName, - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "env": "prod", }, }) @@ -394,7 +394,7 @@ func Test_Registry_MultipleServicesVersionFiltering(t *testing.T) { service1 := &gsvc.LocalService{ Name: testServiceName, Version: "1.0.0", - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "region": "us-east-1", }, Endpoints: []gsvc.Endpoint{ @@ -405,7 +405,7 @@ func Test_Registry_MultipleServicesVersionFiltering(t *testing.T) { service2 := &gsvc.LocalService{ Name: testServiceName, Version: "2.0.0", - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "region": "us-west-1", }, Endpoints: []gsvc.Endpoint{ diff --git a/contrib/registry/consul/consul_watcher.go b/contrib/registry/consul/consul_watcher.go index 865b6e28c41..7a648f44a14 100644 --- a/contrib/registry/consul/consul_watcher.go +++ b/contrib/registry/consul/consul_watcher.go @@ -59,7 +59,7 @@ func (w *Watcher) watch() { w.mu.Unlock() // Create watch plan - plan, err := watch.Parse(map[string]interface{}{ + plan, err := watch.Parse(map[string]any{ "type": "service", "service": w.key, }) @@ -72,7 +72,7 @@ func (w *Watcher) watch() { w.mu.Unlock() // Set handler - plan.Handler = func(idx uint64, data interface{}) { + plan.Handler = func(idx uint64, data any) { // Check if watcher is closed select { case <-w.closeChan: @@ -169,7 +169,7 @@ func (w *Watcher) Services() ([]gsvc.Service, error) { var services []gsvc.Service for _, entry := range entries { if entry.Checks.AggregatedStatus() == api.HealthPassing { - metadata := make(map[string]interface{}) + metadata := make(map[string]any) if entry.Service.Meta != nil { if metaStr, ok := entry.Service.Meta["metadata"]; ok { if err := json.Unmarshal([]byte(metaStr), &metadata); err != nil { diff --git a/contrib/registry/etcd/etcd_z_test.go b/contrib/registry/etcd/etcd_z_test.go index c4a8194db17..dab24af7f01 100644 --- a/contrib/registry/etcd/etcd_z_test.go +++ b/contrib/registry/etcd/etcd_z_test.go @@ -25,7 +25,7 @@ func TestRegistry(t *testing.T) { svc := &gsvc.LocalService{ Name: guid.S(), Endpoints: gsvc.NewEndpoints("127.0.0.1:8888"), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, } @@ -59,7 +59,7 @@ func TestRegistry(t *testing.T) { gtest.C(t, func(t *gtest.T) { result, err := registry.Search(ctx, gsvc.SearchInput{ Name: svc.GetName(), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, }) @@ -70,7 +70,7 @@ func TestRegistry(t *testing.T) { gtest.C(t, func(t *gtest.T) { result, err := registry.Search(ctx, gsvc.SearchInput{ Name: svc.GetName(), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "grpc", }, }) @@ -93,7 +93,7 @@ func TestWatch(t *testing.T) { svc1 := &gsvc.LocalService{ Name: guid.S(), Endpoints: gsvc.NewEndpoints("127.0.0.1:8888"), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, } diff --git a/contrib/registry/file/file_z_basic_test.go b/contrib/registry/file/file_z_basic_test.go index 61bd22aa6c6..7cff0854ade 100644 --- a/contrib/registry/file/file_z_basic_test.go +++ b/contrib/registry/file/file_z_basic_test.go @@ -29,7 +29,7 @@ func TestRegistry(t *testing.T) { svc := &gsvc.LocalService{ Name: guid.S(), Endpoints: gsvc.NewEndpoints("127.0.0.1:8888"), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, } @@ -63,7 +63,7 @@ func TestRegistry(t *testing.T) { gtest.C(t, func(t *gtest.T) { result, err := registry.Search(ctx, gsvc.SearchInput{ Name: svc.GetName(), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, }) @@ -74,7 +74,7 @@ func TestRegistry(t *testing.T) { gtest.C(t, func(t *gtest.T) { result, err := registry.Search(ctx, gsvc.SearchInput{ Name: svc.GetName(), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "grpc", }, }) @@ -99,7 +99,7 @@ func TestWatch(t *testing.T) { svc1 := &gsvc.LocalService{ Name: guid.S(), Endpoints: gsvc.NewEndpoints("127.0.0.1:8888"), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, } diff --git a/contrib/registry/nacos/nacos_z_test.go b/contrib/registry/nacos/nacos_z_test.go index f610384929e..6ebacd8adad 100644 --- a/contrib/registry/nacos/nacos_z_test.go +++ b/contrib/registry/nacos/nacos_z_test.go @@ -40,7 +40,7 @@ func TestRegistry(t *testing.T) { svc := &gsvc.LocalService{ Name: guid.S(), Endpoints: gsvc.NewEndpoints("127.0.0.1:8888"), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, } @@ -74,7 +74,7 @@ func TestRegistry(t *testing.T) { gtest.C(t, func(t *gtest.T) { result, err := registry.Search(ctx, gsvc.SearchInput{ Name: svc.GetName(), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, }) @@ -85,7 +85,7 @@ func TestRegistry(t *testing.T) { gtest.C(t, func(t *gtest.T) { result, err := registry.Search(ctx, gsvc.SearchInput{ Name: svc.GetName(), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "grpc", }, }) @@ -115,7 +115,7 @@ func TestWatch(t *testing.T) { svc1 := &gsvc.LocalService{ Name: guid.S(), Endpoints: gsvc.NewEndpoints("127.0.0.1:8888"), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, } @@ -149,7 +149,7 @@ func TestWatch(t *testing.T) { svc2 := &gsvc.LocalService{ Name: svc1.Name, Endpoints: gsvc.NewEndpoints("127.0.0.2:9999"), - Metadata: map[string]interface{}{ + Metadata: map[string]any{ "protocol": "https", }, } diff --git a/contrib/registry/polaris/polaris_registry.go b/contrib/registry/polaris/polaris_registry.go index a02e272b17d..2e703d130b2 100644 --- a/contrib/registry/polaris/polaris_registry.go +++ b/contrib/registry/polaris/polaris_registry.go @@ -28,17 +28,17 @@ func (r *Registry) Register(ctx context.Context, service gsvc.Service) (gsvc.Ser for _, endpoint := range service.GetEndpoints() { // medata var ( - rmd map[string]interface{} + rmd map[string]any serviceName = service.GetPrefix() serviceVersion = service.GetVersion() ) if service.GetMetadata().IsEmpty() { - rmd = map[string]interface{}{ + rmd = map[string]any{ metadataKeyKind: gsvc.DefaultProtocol, metadataKeyVersion: serviceVersion, } } else { - rmd = make(map[string]interface{}, len(service.GetMetadata())+2) + rmd = make(map[string]any, len(service.GetMetadata())+2) rmd[metadataKeyKind] = gsvc.DefaultProtocol if protocol, ok := service.GetMetadata()[gsvc.MDProtocol]; ok { rmd[metadataKeyKind] = gconv.String(protocol) diff --git a/contrib/registry/polaris/polaris_z_test.go b/contrib/registry/polaris/polaris_z_test.go index 3062f5785a2..e40c4888abe 100644 --- a/contrib/registry/polaris/polaris_z_test.go +++ b/contrib/registry/polaris/polaris_z_test.go @@ -37,7 +37,7 @@ func TestRegistry_Register(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-register-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } @@ -69,7 +69,7 @@ func TestRegistry_Deregister(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-deregister-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } @@ -101,19 +101,19 @@ func TestRegistryMany(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-1-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } svc1 := &gsvc.LocalService{ Name: "goframe-provider-2-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9001"), } svc2 := &gsvc.LocalService{ Name: "goframe-provider-3-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9002"), } @@ -163,7 +163,7 @@ func TestRegistry_Search(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-4-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } @@ -207,7 +207,7 @@ func TestRegistry_Watch(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-5-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } @@ -279,7 +279,7 @@ func TestWatcher_Proceed(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-5-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } @@ -289,7 +289,7 @@ func TestWatcher_Proceed(t *testing.T) { svc1 := &gsvc.LocalService{ Name: "goframe-provider-5-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9001"), } @@ -408,7 +408,7 @@ func BenchmarkRegister(b *testing.B) { svc := &gsvc.LocalService{ Name: "goframe-provider-0-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } for i := 0; i < b.N; i++ { @@ -449,21 +449,21 @@ func TestRegistryManyForEndpoints(t *testing.T) { svc := &gsvc.LocalService{ Name: serviceName, Version: version, - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints(endpointOne), } svc1 := &gsvc.LocalService{ Name: serviceName, Version: version, - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints(endpointTwo), } svc2 := &gsvc.LocalService{ Name: serviceName, Version: version, - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints(endpointThree), } @@ -541,7 +541,7 @@ func TestWatcher_Close(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-close-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } @@ -580,7 +580,7 @@ func TestGetKey(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-key-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } @@ -610,7 +610,7 @@ func TestService_GetPrefix(t *testing.T) { Service: &gsvc.LocalService{ Name: "goframe-provider-0-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), }, ID: "test", @@ -623,7 +623,7 @@ func TestService_GetPrefix(t *testing.T) { Service: &gsvc.LocalService{ Name: "goframe-provider-1-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9001"), }, ID: "test", @@ -636,7 +636,7 @@ func TestService_GetPrefix(t *testing.T) { Service: &gsvc.LocalService{ Name: "goframe-provider-2-tcp", Version: "latest", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9002"), }, ID: "latest", @@ -676,7 +676,7 @@ func TestService_GetKey(t *testing.T) { Deployment: gsvc.DefaultDeployment, Name: "goframe-provider-0-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), }, ID: "test", @@ -691,7 +691,7 @@ func TestService_GetKey(t *testing.T) { Deployment: gsvc.DefaultDeployment, Name: "goframe-provider-1-tcp", Version: "latest", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9001"), }, ID: "latest", @@ -706,7 +706,7 @@ func TestService_GetKey(t *testing.T) { Deployment: gsvc.DefaultDeployment, Name: "goframe-provider-2-tcp", Version: "latest", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9002"), }, ID: "latest", diff --git a/contrib/registry/zookeeper/zookeeper_discovery.go b/contrib/registry/zookeeper/zookeeper_discovery.go index 53eee5288d4..7ef62f8c4e5 100644 --- a/contrib/registry/zookeeper/zookeeper_discovery.go +++ b/contrib/registry/zookeeper/zookeeper_discovery.go @@ -20,7 +20,7 @@ import ( // Search searches and returns services with specified condition. func (r *Registry) Search(_ context.Context, in gsvc.SearchInput) ([]gsvc.Service, error) { prefix := strings.Trim(strings.ReplaceAll(in.Prefix, "/", "-"), "-") - instances, err, _ := r.group.Do(prefix, func() (interface{}, error) { + instances, err, _ := r.group.Do(prefix, func() (any, error) { serviceNamePath := path.Join(r.opts.namespace, prefix) servicesID, _, err := r.conn.Children(serviceNamePath) if err != nil { diff --git a/contrib/registry/zookeeper/zookeeper_watcher.go b/contrib/registry/zookeeper/zookeeper_watcher.go index 5efea6f57ef..c20ae634b59 100644 --- a/contrib/registry/zookeeper/zookeeper_watcher.go +++ b/contrib/registry/zookeeper/zookeeper_watcher.go @@ -69,7 +69,7 @@ func (w *watcher) Proceed() ([]gsvc.Service, error) { func (w *watcher) getServicesByPrefix() ([]gsvc.Service, error) { prefix := strings.Trim(strings.ReplaceAll(w.prefix, "/", "-"), "-") serviceNamePath := path.Join(w.nameSpace, prefix) - instances, err, _ := w.group.Do(serviceNamePath, func() (interface{}, error) { + instances, err, _ := w.group.Do(serviceNamePath, func() (any, error) { servicesID, _, err := w.conn.Children(serviceNamePath) if err != nil { return nil, gerror.Wrapf( diff --git a/contrib/registry/zookeeper/zookeeper_z_test.go b/contrib/registry/zookeeper/zookeeper_z_test.go index 207e8237634..2dfdd3e195f 100644 --- a/contrib/registry/zookeeper/zookeeper_z_test.go +++ b/contrib/registry/zookeeper/zookeeper_z_test.go @@ -24,7 +24,7 @@ func TestRegistry(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-0-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } @@ -46,19 +46,19 @@ func TestRegistryMany(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-1-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } svc1 := &gsvc.LocalService{ Name: "goframe-provider-2-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9001"), } svc2 := &gsvc.LocalService{ Name: "goframe-provider-3-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9002"), } @@ -101,7 +101,7 @@ func TestGetService(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-4-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } @@ -138,7 +138,7 @@ func TestWatch(t *testing.T) { svc := &gsvc.LocalService{ Name: "goframe-provider-4-tcp", Version: "test", - Metadata: map[string]interface{}{"app": "goframe", gsvc.MDProtocol: "tcp"}, + Metadata: map[string]any{"app": "goframe", gsvc.MDProtocol: "tcp"}, Endpoints: gsvc.NewEndpoints("127.0.0.1:9000"), } t.Log("watch") diff --git a/contrib/rpc/grpcx/grpcx_grpc_server_unary.go b/contrib/rpc/grpcx/grpcx_grpc_server_unary.go index 5658da3b6b3..0d43ff901af 100644 --- a/contrib/rpc/grpcx/grpcx_grpc_server_unary.go +++ b/contrib/rpc/grpcx/grpcx_grpc_server_unary.go @@ -21,8 +21,8 @@ import ( // UnaryLogger is the default unary interceptor for logging purpose. func (s *GrpcServer) UnaryLogger( - ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, -) (interface{}, error) { + ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, +) (any, error) { var ( start = time.Now() res, err = handler(ctx, req) @@ -35,7 +35,7 @@ func (s *GrpcServer) UnaryLogger( // handleAccessLog handles the access logging for server. func (s *GrpcServer) handleAccessLog( - ctx context.Context, err error, duration time.Duration, info *grpc.UnaryServerInfo, req, res interface{}, + ctx context.Context, err error, duration time.Duration, info *grpc.UnaryServerInfo, req, res any, ) { if !s.config.AccessLogEnabled { return @@ -49,7 +49,7 @@ func (s *GrpcServer) handleAccessLog( // handleErrorLog handles the error logging for server. func (s *GrpcServer) handleErrorLog( - ctx context.Context, err error, duration time.Duration, info *grpc.UnaryServerInfo, req, res interface{}, + ctx context.Context, err error, duration time.Duration, info *grpc.UnaryServerInfo, req, res any, ) { // It does nothing if error logging is custom disabled. if !s.config.ErrorLogEnabled || err == nil { diff --git a/contrib/rpc/grpcx/grpcx_interceptor_client.go b/contrib/rpc/grpcx/grpcx_interceptor_client.go index bc185d7d1b5..5203c9fcdf7 100644 --- a/contrib/rpc/grpcx/grpcx_interceptor_client.go +++ b/contrib/rpc/grpcx/grpcx_interceptor_client.go @@ -20,7 +20,7 @@ import ( // UnaryError handles the error types converting between grpc and gerror. // Note that, the minus error code is only used locally which will not be sent to other side. -func (c modClient) UnaryError(ctx context.Context, method string, req, reply interface{}, +func (c modClient) UnaryError(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { err := invoker(ctx, method, req, reply, cc, opts...) if err != nil { @@ -37,7 +37,7 @@ func (c modClient) UnaryError(ctx context.Context, method string, req, reply int // UnaryTracing is a unary interceptor for adding tracing feature for gRPC client using OpenTelemetry. func (c modClient) UnaryTracing( - ctx context.Context, method string, req, reply interface{}, + ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { return tracing.UnaryClientInterceptor(ctx, method, req, reply, cc, invoker, opts...) } diff --git a/contrib/rpc/grpcx/grpcx_interceptor_server.go b/contrib/rpc/grpcx/grpcx_interceptor_server.go index 0d968f6a867..cb7bd5fe362 100644 --- a/contrib/rpc/grpcx/grpcx_interceptor_server.go +++ b/contrib/rpc/grpcx/grpcx_interceptor_server.go @@ -40,8 +40,8 @@ func (s modServer) ChainStream(interceptors ...grpc.StreamServerInterceptor) grp // UnaryError is the default unary interceptor for error converting from custom error to grpc error. func (s modServer) UnaryError( - ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, -) (interface{}, error) { + ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, +) (any, error) { res, err := handler(ctx, req) if err != nil { code := gerror.Code(err) @@ -54,8 +54,8 @@ func (s modServer) UnaryError( // UnaryRecover is the first interceptor that keep server not down from panics. func (s modServer) UnaryRecover( - ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, -) (res interface{}, err error) { + ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, +) (res any, err error) { gutil.TryCatch(ctx, func(ctx2 context.Context) { res, err = handler(ctx, req) }, func(ctx context.Context, exception error) { @@ -66,8 +66,8 @@ func (s modServer) UnaryRecover( // UnaryValidate Common validation unary interpreter. func (s modServer) UnaryValidate( - ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, -) (interface{}, error) { + ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, +) (any, error) { // It does nothing if there's no validation tag in the struct definition. if err := g.Validator().Data(req).Run(ctx); err != nil { return nil, gerror.NewCode( @@ -79,8 +79,8 @@ func (s modServer) UnaryValidate( } func (s modServer) UnaryAllowNilRes( - ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, -) (interface{}, error) { + ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, +) (any, error) { res, err := handler(ctx, req) if g.IsNil(res) { res = proto.Message(nil) @@ -91,14 +91,14 @@ func (s modServer) UnaryAllowNilRes( // UnaryTracing is a unary interceptor for adding tracing feature for gRPC server using OpenTelemetry. // The tracing feature is builtin enabled. func (s modServer) UnaryTracing( - ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, -) (interface{}, error) { + ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, +) (any, error) { return tracing.UnaryServerInterceptor(ctx, req, info, handler) } // StreamTracing is a stream unary interceptor for adding tracing feature for gRPC server using OpenTelemetry. func (s modServer) StreamTracing( - srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, + srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, ) error { return tracing.StreamServerInterceptor(srv, ss, info, handler) } diff --git a/contrib/rpc/grpcx/internal/resolver/resolver_resolver.go b/contrib/rpc/grpcx/internal/resolver/resolver_resolver.go index 7ba12ca3155..7969d1c9b43 100644 --- a/contrib/rpc/grpcx/internal/resolver/resolver_resolver.go +++ b/contrib/rpc/grpcx/internal/resolver/resolver_resolver.go @@ -110,7 +110,7 @@ func (r *Resolver) ResolveNow(options resolver.ResolveNowOptions) { } -func newAttributesFromMetadata(metadata map[string]interface{}) *attributes.Attributes { +func newAttributesFromMetadata(metadata map[string]any) *attributes.Attributes { var a *attributes.Attributes for k, v := range metadata { if a == nil { diff --git a/contrib/rpc/grpcx/internal/tracing/tracing_interceptor.go b/contrib/rpc/grpcx/internal/tracing/tracing_interceptor.go index e84c21c9273..c45d7416d21 100644 --- a/contrib/rpc/grpcx/internal/tracing/tracing_interceptor.go +++ b/contrib/rpc/grpcx/internal/tracing/tracing_interceptor.go @@ -31,7 +31,7 @@ type messageType attribute.KeyValue // Event adds an event of the messageType to the span associated with the // passed context with id and size (if message is a proto message). -func (m messageType) Event(ctx context.Context, id int, message interface{}) { +func (m messageType) Event(ctx context.Context, id int, message any) { span := trace.SpanFromContext(ctx) if p, ok := message.(proto.Message); ok { span.AddEvent("message", trace.WithAttributes( @@ -81,7 +81,7 @@ type clientStream struct { var _ = proto.Marshal -func (w *clientStream) RecvMsg(m interface{}) error { +func (w *clientStream) RecvMsg(m any) error { err := w.ClientStream.RecvMsg(m) if err == nil && !w.desc.ServerStreams { @@ -98,7 +98,7 @@ func (w *clientStream) RecvMsg(m interface{}) error { return err } -func (w *clientStream) SendMsg(m interface{}) error { +func (w *clientStream) SendMsg(m any) error { err := w.ClientStream.SendMsg(m) w.sentMessageID++ @@ -196,7 +196,7 @@ func (w *serverStream) Context() context.Context { return w.ctx } -func (w *serverStream) RecvMsg(m interface{}) error { +func (w *serverStream) RecvMsg(m any) error { err := w.ServerStream.RecvMsg(m) if err == nil { @@ -207,7 +207,7 @@ func (w *serverStream) RecvMsg(m interface{}) error { return err } -func (w *serverStream) SendMsg(m interface{}) error { +func (w *serverStream) SendMsg(m any) error { err := w.ServerStream.SendMsg(m) w.sentMessageID++ diff --git a/contrib/rpc/grpcx/internal/tracing/tracing_interceptor_client.go b/contrib/rpc/grpcx/internal/tracing/tracing_interceptor_client.go index b688446f730..97e73dd8097 100644 --- a/contrib/rpc/grpcx/internal/tracing/tracing_interceptor_client.go +++ b/contrib/rpc/grpcx/internal/tracing/tracing_interceptor_client.go @@ -27,7 +27,7 @@ import ( // UnaryClientInterceptor returns a grpc.UnaryClientInterceptor suitable // for use in a grpc.Dial call. -func UnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, +func UnaryClientInterceptor(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, callOpts ...grpc.CallOption) error { tracer := otel.GetTracerProvider().Tracer( tracingInstrumentGrpcClient, diff --git a/contrib/rpc/grpcx/internal/tracing/tracing_interceptor_server.go b/contrib/rpc/grpcx/internal/tracing/tracing_interceptor_server.go index 7395d5cf052..919f35cf095 100644 --- a/contrib/rpc/grpcx/internal/tracing/tracing_interceptor_server.go +++ b/contrib/rpc/grpcx/internal/tracing/tracing_interceptor_server.go @@ -28,7 +28,7 @@ import ( // UnaryServerInterceptor returns a grpc.UnaryServerInterceptor suitable // for usage in a grpc.NewServer call. -func UnaryServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { +func UnaryServerInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { tracer := otel.GetTracerProvider().Tracer( tracingInstrumentGrpcServer, trace.WithInstrumentationVersion(gf.VERSION), @@ -75,7 +75,7 @@ func UnaryServerInterceptor(ctx context.Context, req interface{}, info *grpc.Una // StreamServerInterceptor returns a grpc.StreamServerInterceptor suitable // for use in a grpc.NewServer call. -func StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func StreamServerInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { tracer := otel.GetTracerProvider().Tracer( tracingInstrumentGrpcServer, trace.WithInstrumentationVersion(gf.VERSION), diff --git a/contrib/rpc/grpcx/internal/utils/utils.go b/contrib/rpc/grpcx/internal/utils/utils.go index 6f84d6d194a..721552ff392 100644 --- a/contrib/rpc/grpcx/internal/utils/utils.go +++ b/contrib/rpc/grpcx/internal/utils/utils.go @@ -26,7 +26,7 @@ func MarshalPbMessageToJsonString(msg proto.Message) string { return protoJSONMarshaller.Format(msg) } -func MarshalMessageToJsonStringForTracing(value interface{}, msgType string, maxBytes int) string { +func MarshalMessageToJsonStringForTracing(value any, msgType string, maxBytes int) string { var messageContent string if msg, ok := value.(proto.Message); ok { if proto.Size(msg) <= maxBytes { diff --git a/contrib/rpc/grpcx/testdata/protobuf/helloworld.pb.go b/contrib/rpc/grpcx/testdata/protobuf/helloworld.pb.go index 8af3b213b5f..58113fccc46 100644 --- a/contrib/rpc/grpcx/testdata/protobuf/helloworld.pb.go +++ b/contrib/rpc/grpcx/testdata/protobuf/helloworld.pb.go @@ -9,10 +9,11 @@ package protobuf import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) const ( @@ -151,7 +152,7 @@ func file_helloworld_proto_rawDescGZIP() []byte { } var file_helloworld_proto_msgTypes = make([]protoimpl.MessageInfo, 2) -var file_helloworld_proto_goTypes = []interface{}{ +var file_helloworld_proto_goTypes = []any{ (*HelloRequest)(nil), // 0: protobuf.HelloRequest (*HelloReply)(nil), // 1: protobuf.HelloReply } @@ -171,7 +172,7 @@ func file_helloworld_proto_init() { return } if !protoimpl.UnsafeEnabled { - file_helloworld_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + file_helloworld_proto_msgTypes[0].Exporter = func(v any, i int) any { switch v := v.(*HelloRequest); i { case 0: return &v.state @@ -183,7 +184,7 @@ func file_helloworld_proto_init() { return nil } } - file_helloworld_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + file_helloworld_proto_msgTypes[1].Exporter = func(v any, i int) any { switch v := v.(*HelloReply); i { case 0: return &v.state diff --git a/contrib/rpc/grpcx/testdata/protobuf/helloworld_grpc.pb.go b/contrib/rpc/grpcx/testdata/protobuf/helloworld_grpc.pb.go index af29539f4ee..95e18a2c958 100644 --- a/contrib/rpc/grpcx/testdata/protobuf/helloworld_grpc.pb.go +++ b/contrib/rpc/grpcx/testdata/protobuf/helloworld_grpc.pb.go @@ -8,6 +8,7 @@ package protobuf import ( context "context" + grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" @@ -72,7 +73,7 @@ func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) { s.RegisterService(&Greeter_ServiceDesc, srv) } -func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { +func _Greeter_SayHello_Handler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) { in := new(HelloRequest) if err := dec(in); err != nil { return nil, err @@ -84,7 +85,7 @@ func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(in Server: srv, FullMethod: "/protobuf.Greeter/SayHello", } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { + handler := func(ctx context.Context, req any) (any, error) { return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) } return interceptor(ctx, in, info, handler) diff --git a/contrib/sdk/httpclient/httpclient.go b/contrib/sdk/httpclient/httpclient.go index 272f3a6369e..ceb4d93d8cd 100644 --- a/contrib/sdk/httpclient/httpclient.go +++ b/contrib/sdk/httpclient/httpclient.go @@ -49,7 +49,7 @@ func New(config Config) *Client { } // Request sends request to service by struct object `req`, and receives response to struct object `res`. -func (c *Client) Request(ctx context.Context, req, res interface{}) error { +func (c *Client) Request(ctx context.Context, req, res any) error { var ( method = gmeta.Get(req, gtag.Method).String() path = gmeta.Get(req, gtag.Path).String() @@ -68,7 +68,7 @@ func (c *Client) Request(ctx context.Context, req, res interface{}) error { } // Get sends a request using GET method. -func (c *Client) Get(ctx context.Context, path string, in, out interface{}) error { +func (c *Client) Get(ctx context.Context, path string, in, out any) error { // TODO: Path params will also be built in urlParams, not graceful now. if urlParams := ghttp.BuildParams(in); urlParams != "" && urlParams != "{}" { path += "?" + urlParams @@ -80,7 +80,7 @@ func (c *Client) Get(ctx context.Context, path string, in, out interface{}) erro return c.HandleResponse(ctx, res, out) } -func (c *Client) handlePath(path string, in interface{}) string { +func (c *Client) handlePath(path string, in any) string { if gstr.Contains(path, "{") { data := gconv.MapStrStr(in) path, _ = gregex.ReplaceStringFuncMatch(`\{(\w+)\}`, path, func(match []string) string { diff --git a/contrib/sdk/httpclient/httpclient_handler.go b/contrib/sdk/httpclient/httpclient_handler.go index eca6eed9e0d..44cb41c82eb 100644 --- a/contrib/sdk/httpclient/httpclient_handler.go +++ b/contrib/sdk/httpclient/httpclient_handler.go @@ -22,7 +22,7 @@ import ( type Handler interface { // HandleResponse handles the http response and transforms its body to the specified object. // The parameter `out` specifies the object that the response body is transformed to. - HandleResponse(ctx context.Context, res *gclient.Response, out interface{}) error + HandleResponse(ctx context.Context, res *gclient.Response, out any) error } // DefaultHandler handle ghttp.DefaultHandlerResponse of json format. @@ -41,7 +41,7 @@ func NewDefaultHandler(logger *glog.Logger, rawRump bool) *DefaultHandler { } } -func (h DefaultHandler) HandleResponse(ctx context.Context, res *gclient.Response, out interface{}) error { +func (h DefaultHandler) HandleResponse(ctx context.Context, res *gclient.Response, out any) error { defer res.Close() if h.RawDump { h.Logger.Debugf(ctx, "raw request&response:\n%s", res.Raw()) diff --git a/contrib/sdk/httpclient/httpclient_z_unit_feature_handler_test.go b/contrib/sdk/httpclient/httpclient_z_unit_feature_handler_test.go index 2babecd8801..9a49aab2504 100644 --- a/contrib/sdk/httpclient/httpclient_z_unit_feature_handler_test.go +++ b/contrib/sdk/httpclient/httpclient_z_unit_feature_handler_test.go @@ -66,7 +66,7 @@ func Test_HttpClient_With_Default_Handler(t *testing.T) { type CustomHandler struct{} -func (c CustomHandler) HandleResponse(ctx context.Context, res *gclient.Response, out interface{}) error { +func (c CustomHandler) HandleResponse(ctx context.Context, res *gclient.Response, out any) error { defer res.Close() if pointer, ok := out.(*string); ok { *pointer = res.ReadAllString() diff --git a/crypto/gcrc32/gcrc32.go b/crypto/gcrc32/gcrc32.go index bef114b09d2..79546b2196e 100644 --- a/crypto/gcrc32/gcrc32.go +++ b/crypto/gcrc32/gcrc32.go @@ -15,6 +15,6 @@ import ( // Encrypt encrypts any type of variable using CRC32 algorithms. // It uses gconv package to convert `v` to its bytes type. -func Encrypt(v interface{}) uint32 { +func Encrypt(v any) uint32 { return crc32.ChecksumIEEE(gconv.Bytes(v)) } diff --git a/crypto/gmd5/gmd5.go b/crypto/gmd5/gmd5.go index 5b28bdb8066..c5797473529 100644 --- a/crypto/gmd5/gmd5.go +++ b/crypto/gmd5/gmd5.go @@ -19,14 +19,14 @@ import ( // Encrypt encrypts any type of variable using MD5 algorithms. // It uses gconv package to convert `v` to its bytes type. -func Encrypt(data interface{}) (encrypt string, err error) { +func Encrypt(data any) (encrypt string, err error) { return EncryptBytes(gconv.Bytes(data)) } // MustEncrypt encrypts any type of variable using MD5 algorithms. // It uses gconv package to convert `v` to its bytes type. // It panics if any error occurs. -func MustEncrypt(data interface{}) string { +func MustEncrypt(data any) string { result, err := Encrypt(data) if err != nil { panic(err) diff --git a/crypto/gsha1/gsha1.go b/crypto/gsha1/gsha1.go index fea46335f70..8a3d5e8391e 100644 --- a/crypto/gsha1/gsha1.go +++ b/crypto/gsha1/gsha1.go @@ -19,7 +19,7 @@ import ( // Encrypt encrypts any type of variable using SHA1 algorithms. // It uses package gconv to convert `v` to its bytes type. -func Encrypt(v interface{}) string { +func Encrypt(v any) string { r := sha1.Sum(gconv.Bytes(v)) return hex.EncodeToString(r[:]) } diff --git a/database/gdb/gdb.go b/database/gdb/gdb.go index ff84576561a..e9560a22467 100644 --- a/database/gdb/gdb.go +++ b/database/gdb/gdb.go @@ -43,10 +43,10 @@ type DB interface { // Model("user u, user_detail ud") // 2. Model name with alias: Model("user", "u") // Also see Core.Model. - Model(tableNameOrStruct ...interface{}) *Model + Model(tableNameOrStruct ...any) *Model // Raw creates and returns a model based on a raw sql not a table. - Raw(rawSql string, args ...interface{}) *Model + Raw(rawSql string, args ...any) *Model // Schema switches to a specified schema. // Also see Core.Schema. @@ -54,7 +54,7 @@ type DB interface { // With creates and returns an ORM model based on metadata of given object. // Also see Core.With. - With(objects ...interface{}) *Model + With(objects ...any) *Model // Open creates a raw connection object for database with given node configuration. // Note that it is not recommended using the function manually. @@ -79,11 +79,11 @@ type DB interface { // Query executes a SQL query that returns rows using given SQL and arguments. // The args are for any placeholder parameters in the query. - Query(ctx context.Context, sql string, args ...interface{}) (Result, error) + Query(ctx context.Context, sql string, args ...any) (Result, error) // Exec executes a SQL query that doesn't return rows (e.g., INSERT, UPDATE, DELETE). // It returns sql.Result for accessing LastInsertId or RowsAffected. - Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error) + Exec(ctx context.Context, sql string, args ...any) (sql.Result, error) // Prepare creates a prepared statement for later queries or executions. // The execOnMaster parameter determines whether the statement executes on master node. @@ -96,32 +96,32 @@ type DB interface { // Insert inserts one or multiple records into table. // The data can be a map, struct, or slice of maps/structs. // The optional batch parameter specifies the batch size for bulk inserts. - Insert(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) + Insert(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) // InsertIgnore inserts records but ignores duplicate key errors. // It works like Insert but adds IGNORE keyword to the SQL statement. - InsertIgnore(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) + InsertIgnore(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) // InsertAndGetId inserts a record and returns the auto-generated ID. // It's a convenience method combining Insert with LastInsertId. - InsertAndGetId(ctx context.Context, table string, data interface{}, batch ...int) (int64, error) + InsertAndGetId(ctx context.Context, table string, data any, batch ...int) (int64, error) // Replace inserts or replaces records using REPLACE INTO syntax. // Existing records with same unique key will be deleted and re-inserted. - Replace(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) + Replace(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) // Save inserts or updates records using INSERT ... ON DUPLICATE KEY UPDATE syntax. // It updates existing records instead of replacing them entirely. - Save(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) + Save(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) // Update updates records in table that match the condition. // The data can be a map or struct containing the new values. // The condition specifies the WHERE clause with optional placeholder args. - Update(ctx context.Context, table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) + Update(ctx context.Context, table string, data any, condition any, args ...any) (sql.Result, error) // Delete deletes records from table that match the condition. // The condition specifies the WHERE clause with optional placeholder args. - Delete(ctx context.Context, table string, condition interface{}, args ...interface{}) (sql.Result, error) + Delete(ctx context.Context, table string, condition any, args ...any) (sql.Result, error) // =========================================================================== // Internal APIs for CRUD, which can be overwritten by custom CRUD implements. @@ -129,7 +129,7 @@ type DB interface { // DoSelect executes a SELECT query using the given link and returns the result. // This is an internal method that can be overridden by custom implementations. - DoSelect(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error) + DoSelect(ctx context.Context, link Link, sql string, args ...any) (result Result, err error) // DoInsert performs the actual INSERT operation with given options. // This is an internal method that can be overridden by custom implementations. @@ -137,23 +137,23 @@ type DB interface { // DoUpdate performs the actual UPDATE operation. // This is an internal method that can be overridden by custom implementations. - DoUpdate(ctx context.Context, link Link, table string, data interface{}, condition string, args ...interface{}) (result sql.Result, err error) + DoUpdate(ctx context.Context, link Link, table string, data any, condition string, args ...any) (result sql.Result, err error) // DoDelete performs the actual DELETE operation. // This is an internal method that can be overridden by custom implementations. - DoDelete(ctx context.Context, link Link, table string, condition string, args ...interface{}) (result sql.Result, err error) + DoDelete(ctx context.Context, link Link, table string, condition string, args ...any) (result sql.Result, err error) // DoQuery executes a query that returns rows. // This is an internal method that can be overridden by custom implementations. - DoQuery(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error) + DoQuery(ctx context.Context, link Link, sql string, args ...any) (result Result, err error) // DoExec executes a query that doesn't return rows. // This is an internal method that can be overridden by custom implementations. - DoExec(ctx context.Context, link Link, sql string, args ...interface{}) (result sql.Result, err error) + DoExec(ctx context.Context, link Link, sql string, args ...any) (result sql.Result, err error) // DoFilter processes and filters SQL and args before execution. // This is an internal method that can be overridden to implement custom SQL filtering. - DoFilter(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) + DoFilter(ctx context.Context, link Link, sql string, args []any) (newSql string, newArgs []any, err error) // DoCommit handles the actual commit operation for transactions. // This is an internal method that can be overridden by custom implementations. @@ -169,27 +169,27 @@ type DB interface { // GetAll executes a query and returns all rows as Result. // It's a convenience wrapper around Query. - GetAll(ctx context.Context, sql string, args ...interface{}) (Result, error) + GetAll(ctx context.Context, sql string, args ...any) (Result, error) // GetOne executes a query and returns the first row as Record. // It's useful when you expect only one row to be returned. - GetOne(ctx context.Context, sql string, args ...interface{}) (Record, error) + GetOne(ctx context.Context, sql string, args ...any) (Record, error) // GetValue executes a query and returns the first column of the first row. // It's useful for queries like SELECT COUNT(*) or getting a single value. - GetValue(ctx context.Context, sql string, args ...interface{}) (Value, error) + GetValue(ctx context.Context, sql string, args ...any) (Value, error) // GetArray executes a query and returns the first column of all rows. // It's useful for queries like SELECT id FROM table. - GetArray(ctx context.Context, sql string, args ...interface{}) ([]Value, error) + GetArray(ctx context.Context, sql string, args ...any) ([]Value, error) // GetCount executes a COUNT query and returns the result as an integer. // It's a convenience method for counting rows. - GetCount(ctx context.Context, sql string, args ...interface{}) (int, error) + GetCount(ctx context.Context, sql string, args ...any) (int, error) // GetScan executes a query and scans the result into the given object pointer. // It automatically maps database columns to struct fields or slice elements. - GetScan(ctx context.Context, objPointer interface{}, sql string, args ...interface{}) error + GetScan(ctx context.Context, objPointer any, sql string, args ...any) error // Union combines multiple SELECT queries using UNION operator. // It returns a new Model that represents the combined query. @@ -322,18 +322,18 @@ type DB interface { // ConvertValueForField converts a value to the appropriate type for a database field. // It handles type conversion from Go types to database-specific types. - ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) + ConvertValueForField(ctx context.Context, fieldType string, fieldValue any) (any, error) // ConvertValueForLocal converts a database value to the appropriate Go type. // It handles type conversion from database-specific types to Go types. - ConvertValueForLocal(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) + ConvertValueForLocal(ctx context.Context, fieldType string, fieldValue any) (any, error) // GetFormattedDBTypeNameForField returns the formatted database type name and pattern for a field type. GetFormattedDBTypeNameForField(fieldType string) (typeName, typePattern string) // CheckLocalTypeForField checks if a Go value is compatible with a database field type. // It returns the appropriate LocalType and any conversion errors. - CheckLocalTypeForField(ctx context.Context, fieldType string, fieldValue interface{}) (LocalType, error) + CheckLocalTypeForField(ctx context.Context, fieldType string, fieldValue any) (LocalType, error) // FormatUpsert formats an upsert (INSERT ... ON DUPLICATE KEY UPDATE) statement. // It generates the appropriate SQL based on the columns, values, and options provided. @@ -354,15 +354,15 @@ type TX interface { // Raw creates and returns a model based on a raw SQL. // The rawSql can contain placeholders ? and corresponding args. - Raw(rawSql string, args ...interface{}) *Model + Raw(rawSql string, args ...any) *Model // Model creates and returns a Model from given table name/struct. // The parameter can be table name as string, or struct/*struct type. - Model(tableNameQueryOrStruct ...interface{}) *Model + Model(tableNameQueryOrStruct ...any) *Model // With creates and returns a Model from given object. // It automatically analyzes the object and generates corresponding SQL. - With(object interface{}) *Model + With(object any) *Model // =========================================================================== // Nested transaction if necessary. @@ -394,11 +394,11 @@ type TX interface { // Query executes a query that returns rows using given SQL and arguments. // The args are for any placeholder parameters in the query. - Query(sql string, args ...interface{}) (result Result, err error) + Query(sql string, args ...any) (result Result, err error) // Exec executes a query that doesn't return rows. // For example: INSERT, UPDATE, DELETE. - Exec(sql string, args ...interface{}) (sql.Result, error) + Exec(sql string, args ...any) (sql.Result, error) // Prepare creates a prepared statement for later queries or executions. // Multiple queries or executions may be run concurrently from the statement. @@ -410,31 +410,31 @@ type TX interface { // GetAll executes a query and returns all rows as Result. // It's a convenient wrapper for Query. - GetAll(sql string, args ...interface{}) (Result, error) + GetAll(sql string, args ...any) (Result, error) // GetOne executes a query and returns the first row as Record. // It's useful when you expect only one row to be returned. - GetOne(sql string, args ...interface{}) (Record, error) + GetOne(sql string, args ...any) (Record, error) // GetStruct executes a query and scans the result into given struct. // The obj should be a pointer to struct. - GetStruct(obj interface{}, sql string, args ...interface{}) error + GetStruct(obj any, sql string, args ...any) error // GetStructs executes a query and scans all results into given struct slice. // The objPointerSlice should be a pointer to slice of struct. - GetStructs(objPointerSlice interface{}, sql string, args ...interface{}) error + GetStructs(objPointerSlice any, sql string, args ...any) error // GetScan executes a query and scans the result into given variables. // The pointer can be type of struct/*struct/[]struct/[]*struct. - GetScan(pointer interface{}, sql string, args ...interface{}) error + GetScan(pointer any, sql string, args ...any) error // GetValue executes a query and returns the first column of first row. // It's useful for queries like SELECT COUNT(*). - GetValue(sql string, args ...interface{}) (Value, error) + GetValue(sql string, args ...any) (Value, error) // GetCount executes a query that should return a count value. // It's a convenient wrapper for count queries. - GetCount(sql string, args ...interface{}) (int64, error) + GetCount(sql string, args ...any) (int64, error) // =========================================================================== // CRUD. @@ -442,31 +442,31 @@ type TX interface { // Insert inserts one or multiple records into table. // The data can be map/struct/*struct/[]map/[]struct/[]*struct. - Insert(table string, data interface{}, batch ...int) (sql.Result, error) + Insert(table string, data any, batch ...int) (sql.Result, error) // InsertIgnore inserts one or multiple records with IGNORE option. // It ignores records that would cause duplicate key conflicts. - InsertIgnore(table string, data interface{}, batch ...int) (sql.Result, error) + InsertIgnore(table string, data any, batch ...int) (sql.Result, error) // InsertAndGetId inserts one record and returns its id value. // It's commonly used with auto-increment primary key. - InsertAndGetId(table string, data interface{}, batch ...int) (int64, error) + InsertAndGetId(table string, data any, batch ...int) (int64, error) // Replace inserts or replaces records using REPLACE INTO syntax. // Existing records with same unique key will be deleted and re-inserted. - Replace(table string, data interface{}, batch ...int) (sql.Result, error) + Replace(table string, data any, batch ...int) (sql.Result, error) // Save inserts or updates records using INSERT ... ON DUPLICATE KEY UPDATE syntax. // It updates existing records instead of replacing them entirely. - Save(table string, data interface{}, batch ...int) (sql.Result, error) + Save(table string, data any, batch ...int) (sql.Result, error) // Update updates records in table that match given condition. // The data can be map/struct, and condition supports various formats. - Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) + Update(table string, data any, condition any, args ...any) (sql.Result, error) // Delete deletes records from table that match given condition. // The condition supports various formats with optional arguments. - Delete(table string, condition interface{}, args ...interface{}) (sql.Result, error) + Delete(table string, condition any, args ...any) (sql.Result, error) // =========================================================================== // Utility methods. @@ -548,7 +548,7 @@ type DoCommitInput struct { Sql string // Args is the arguments for SQL placeholders. - Args []interface{} + Args []any // Type indicates the type of SQL operation. Type SqlType @@ -578,7 +578,7 @@ type DoCommitOutput struct { Tx TX // RawResult is the underlying result, which might be sql.Result/*sql.Rows/*sql.Row. - RawResult interface{} + RawResult any } // Driver is the interface for integrating sql drivers into package gdb. @@ -590,8 +590,8 @@ type Driver interface { // Link is a common database function wrapper interface. // Note that, any operation using `Link` will have no SQL logging. type Link interface { - QueryContext(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error) - ExecContext(ctx context.Context, sql string, args ...interface{}) (sql.Result, error) + QueryContext(ctx context.Context, sql string, args ...any) (*sql.Rows, error) + ExecContext(ctx context.Context, sql string, args ...any) (sql.Result, error) PrepareContext(ctx context.Context, sql string) (*sql.Stmt, error) IsOnMaster() bool IsTransaction() bool @@ -599,17 +599,17 @@ type Link interface { // Sql is the sql recording struct. type Sql struct { - Sql string // SQL string(may contain reserved char '?'). - Type SqlType // SQL operation type. - Args []interface{} // Arguments for this sql. - Format string // Formatted sql which contains arguments in the sql. - Error error // Execution result. - Start int64 // Start execution timestamp in milliseconds. - End int64 // End execution timestamp in milliseconds. - Group string // Group is the group name of the configuration that the sql is executed from. - Schema string // Schema is the schema name of the configuration that the sql is executed from. - IsTransaction bool // IsTransaction marks whether this sql is executed in transaction. - RowsAffected int64 // RowsAffected marks retrieved or affected number with current sql statement. + Sql string // SQL string(may contain reserved char '?'). + Type SqlType // SQL operation type. + Args []any // Arguments for this sql. + Format string // Formatted sql which contains arguments in the sql. + Error error // Execution result. + Start int64 // Start execution timestamp in milliseconds. + End int64 // End execution timestamp in milliseconds. + Group string // Group is the group name of the configuration that the sql is executed from. + Schema string // Schema is the schema name of the configuration that the sql is executed from. + IsTransaction bool // IsTransaction marks whether this sql is executed in transaction. + RowsAffected int64 // RowsAffected marks retrieved or affected number with current sql statement. } // DoInsertOption is the input struct for function DoInsert. @@ -618,7 +618,7 @@ type DoInsertOption struct { OnDuplicateStr string // OnDuplicateMap is the custom key-value map from `OnDuplicateEx` function for `on duplicated` statement. - OnDuplicateMap map[string]interface{} + OnDuplicateMap map[string]any // OnConflict is the custom conflict key of upsert clause, if the database needs it. OnConflict []string @@ -648,7 +648,7 @@ type TableField struct { Key string // Default is the default value for the field. - Default interface{} + Default any // Extra is the extra information. Eg: auto_increment. Extra string @@ -679,8 +679,8 @@ type ( // Result is the row record array. Result []Record - // Map is alias of map[string]interface{}, which is the most common usage map type. - Map = map[string]interface{} + // Map is alias of map[string]any, which is the most common usage map type. + Map = map[string]any // List is type of map array. List = []Map @@ -964,7 +964,7 @@ func Instance(name ...string) (db DB, err error) { if len(name) > 0 && name[0] != "" { group = name[0] } - v := instances.GetOrSetFuncLock(group, func() interface{} { + v := instances.GetOrSetFuncLock(group, func() any { db, err = NewByGroup(group) return db }) @@ -1099,7 +1099,7 @@ func (c *Core) getSqlDb(master bool, schema ...string) (sqlDb *sql.DB, err error // Cache the underlying connection pool object by node. var ( - instanceCacheFunc = func() interface{} { + instanceCacheFunc = func() any { if sqlDb, err = c.db.Open(node); err != nil { return nil } diff --git a/database/gdb/gdb_core.go b/database/gdb/gdb_core.go index 3665841a364..6de04ab7b08 100644 --- a/database/gdb/gdb_core.go +++ b/database/gdb/gdb_core.go @@ -151,17 +151,17 @@ func (c *Core) Slave(schema ...string) (*sql.DB, error) { } // GetAll queries and returns data records from database. -func (c *Core) GetAll(ctx context.Context, sql string, args ...interface{}) (Result, error) { +func (c *Core) GetAll(ctx context.Context, sql string, args ...any) (Result, error) { return c.db.DoSelect(ctx, nil, sql, args...) } // DoSelect queries and returns data records from database. -func (c *Core) DoSelect(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error) { +func (c *Core) DoSelect(ctx context.Context, link Link, sql string, args ...any) (result Result, err error) { return c.db.DoQuery(ctx, link, sql, args...) } // GetOne queries and returns one record from database. -func (c *Core) GetOne(ctx context.Context, sql string, args ...interface{}) (Record, error) { +func (c *Core) GetOne(ctx context.Context, sql string, args ...any) (Record, error) { list, err := c.db.GetAll(ctx, sql, args...) if err != nil { return nil, err @@ -174,7 +174,7 @@ func (c *Core) GetOne(ctx context.Context, sql string, args ...interface{}) (Rec // GetArray queries and returns data values as slice from database. // Note that if there are multiple columns in the result, it returns just one column values randomly. -func (c *Core) GetArray(ctx context.Context, sql string, args ...interface{}) ([]Value, error) { +func (c *Core) GetArray(ctx context.Context, sql string, args ...any) ([]Value, error) { all, err := c.db.DoSelect(ctx, nil, sql, args...) if err != nil { return nil, err @@ -184,7 +184,7 @@ func (c *Core) GetArray(ctx context.Context, sql string, args ...interface{}) ([ // doGetStruct queries one record from database and converts it to given struct. // The parameter `pointer` should be a pointer to struct. -func (c *Core) doGetStruct(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error { +func (c *Core) doGetStruct(ctx context.Context, pointer any, sql string, args ...any) error { one, err := c.db.GetOne(ctx, sql, args...) if err != nil { return err @@ -194,7 +194,7 @@ func (c *Core) doGetStruct(ctx context.Context, pointer interface{}, sql string, // doGetStructs queries records from database and converts them to given struct. // The parameter `pointer` should be type of struct slice: []struct/[]*struct. -func (c *Core) doGetStructs(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error { +func (c *Core) doGetStructs(ctx context.Context, pointer any, sql string, args ...any) error { all, err := c.db.GetAll(ctx, sql, args...) if err != nil { return err @@ -208,9 +208,9 @@ func (c *Core) doGetStructs(ctx context.Context, pointer interface{}, sql string // If parameter `pointer` is type of struct pointer, it calls GetStruct internally for // the conversion. If parameter `pointer` is type of slice, it calls GetStructs internally // for conversion. -func (c *Core) GetScan(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error { +func (c *Core) GetScan(ctx context.Context, pointer any, sql string, args ...any) error { reflectInfo := reflection.OriginTypeAndKind(pointer) - if reflectInfo.InputKind != reflect.Ptr { + if reflectInfo.InputKind != reflect.Pointer { return gerror.NewCodef( gcode.CodeInvalidParameter, "params should be type of pointer, but got: %v", @@ -236,7 +236,7 @@ func (c *Core) GetScan(ctx context.Context, pointer interface{}, sql string, arg // GetValue queries and returns the field value from database. // The sql should query only one field from database, or else it returns only one // field of the result. -func (c *Core) GetValue(ctx context.Context, sql string, args ...interface{}) (Value, error) { +func (c *Core) GetValue(ctx context.Context, sql string, args ...any) (Value, error) { one, err := c.db.GetOne(ctx, sql, args...) if err != nil { return gvar.New(nil), err @@ -248,7 +248,7 @@ func (c *Core) GetValue(ctx context.Context, sql string, args ...interface{}) (V } // GetCount queries and returns the count from database. -func (c *Core) GetCount(ctx context.Context, sql string, args ...interface{}) (int, error) { +func (c *Core) GetCount(ctx context.Context, sql string, args ...any) (int, error) { // If the query fields do not contain function "COUNT", // it replaces the sql string and adds the "COUNT" function to the fields. if !gregex.IsMatchString(`(?i)SELECT\s+COUNT\(.+\)\s+FROM`, sql) { @@ -277,7 +277,7 @@ func (c *Core) doUnion(ctx context.Context, unionType int, unions ...*Model) *Mo var ( unionTypeStr string composedSqlStr string - composedArgs = make([]interface{}, 0) + composedArgs = make([]any, 0) ) if unionType == unionTypeAll { unionTypeStr = "UNION ALL" @@ -331,7 +331,7 @@ func (c *Core) PingSlave() error { // Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}) // // The parameter `batch` specifies the batch operation count when given data is slice. -func (c *Core) Insert(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) { +func (c *Core) Insert(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) { if len(batch) > 0 { return c.Model(table).Ctx(ctx).Data(data).Batch(batch[0]).Insert() } @@ -347,7 +347,7 @@ func (c *Core) Insert(ctx context.Context, table string, data interface{}, batch // Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}) // // The parameter `batch` specifies the batch operation count when given data is slice. -func (c *Core) InsertIgnore(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) { +func (c *Core) InsertIgnore(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) { if len(batch) > 0 { return c.Model(table).Ctx(ctx).Data(data).Batch(batch[0]).InsertIgnore() } @@ -355,7 +355,7 @@ func (c *Core) InsertIgnore(ctx context.Context, table string, data interface{}, } // InsertAndGetId performs action Insert and returns the last insert id that automatically generated. -func (c *Core) InsertAndGetId(ctx context.Context, table string, data interface{}, batch ...int) (int64, error) { +func (c *Core) InsertAndGetId(ctx context.Context, table string, data any, batch ...int) (int64, error) { if len(batch) > 0 { return c.Model(table).Ctx(ctx).Data(data).Batch(batch[0]).InsertAndGetId() } @@ -374,7 +374,7 @@ func (c *Core) InsertAndGetId(ctx context.Context, table string, data interface{ // The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. // If given data is type of slice, it then does batch replacing, and the optional parameter // `batch` specifies the batch operation count. -func (c *Core) Replace(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) { +func (c *Core) Replace(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) { if len(batch) > 0 { return c.Model(table).Ctx(ctx).Data(data).Batch(batch[0]).Replace() } @@ -392,7 +392,7 @@ func (c *Core) Replace(ctx context.Context, table string, data interface{}, batc // // If given data is type of slice, it then does batch saving, and the optional parameter // `batch` specifies the batch operation count. -func (c *Core) Save(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) { +func (c *Core) Save(ctx context.Context, table string, data any, batch ...int) (sql.Result, error) { if len(batch) > 0 { return c.Model(table).Ctx(ctx).Data(data).Batch(batch[0]).Save() } @@ -436,10 +436,10 @@ func (c *Core) fieldsToSequence(ctx context.Context, table string, fields []stri // InsertOptionIgnore: if there's unique/primary key in the data, it ignores the inserting; func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error) { var ( - keys []string // Field names. - values []string // Value holder string array, like: (?,?,?) - params []interface{} // Values that will be committed to underlying database driver. - onDuplicateStr string // onDuplicateStr is used in "ON DUPLICATE KEY UPDATE" statement. + keys []string // Field names. + values []string // Value holder string array, like: (?,?,?) + params []any // Values that will be committed to underlying database driver. + onDuplicateStr string // onDuplicateStr is used in "ON DUPLICATE KEY UPDATE" statement. ) // ============================================================================================ // Group the list by fields. Different fields to different list. @@ -472,7 +472,7 @@ func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, sqlResult SqlResult rowsAffected int64 ) - keyListMap.Iterator(func(key, value interface{}) bool { + keyListMap.Iterator(func(key, value any) bool { tmpResult, err = c.DoInsert(ctx, link, table, value.(List), option) if err != nil { return false @@ -562,31 +562,31 @@ func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 // User{ Id : 1, UserName : "john"}. -func (c *Core) Update(ctx context.Context, table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) { +func (c *Core) Update(ctx context.Context, table string, data any, condition any, args ...any) (sql.Result, error) { return c.Model(table).Ctx(ctx).Data(data).Where(condition, args...).Update() } // DoUpdate does "UPDATE ... " statement for the table. // This function is usually used for custom interface definition, you do not need to call it manually. -func (c *Core) DoUpdate(ctx context.Context, link Link, table string, data interface{}, condition string, args ...interface{}) (result sql.Result, err error) { +func (c *Core) DoUpdate(ctx context.Context, link Link, table string, data any, condition string, args ...any) (result sql.Result, err error) { table = c.QuotePrefixTableName(table) var ( rv = reflect.ValueOf(data) kind = rv.Kind() ) - if kind == reflect.Ptr { + if kind == reflect.Pointer { rv = rv.Elem() kind = rv.Kind() } var ( - params []interface{} + params []any updates string ) switch kind { case reflect.Map, reflect.Struct: var ( fields []string - dataMap map[string]interface{} + dataMap map[string]any ) dataMap, err = c.ConvertDataForRecord(ctx, data, table) if err != nil { @@ -666,13 +666,13 @@ func (c *Core) DoUpdate(ctx context.Context, link Link, table string, data inter // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 // User{ Id : 1, UserName : "john"}. -func (c *Core) Delete(ctx context.Context, table string, condition interface{}, args ...interface{}) (result sql.Result, err error) { +func (c *Core) Delete(ctx context.Context, table string, condition any, args ...any) (result sql.Result, err error) { return c.Model(table).Ctx(ctx).Where(condition, args...).Delete() } // DoDelete does "DELETE FROM ... " statement for the table. // This function is usually used for custom interface definition, you do not need call it manually. -func (c *Core) DoDelete(ctx context.Context, link Link, table string, condition string, args ...interface{}) (result sql.Result, err error) { +func (c *Core) DoDelete(ctx context.Context, link Link, table string, condition string, args ...any) (result sql.Result, err error) { if link == nil { if link, err = c.MasterLink(); err != nil { return nil, err @@ -752,7 +752,7 @@ func (c *Core) GetTablesWithCache() ([]string, error) { ) result, err := innerMemCache.GetOrSetFuncLock( ctx, cacheKey, - func(ctx context.Context) (interface{}, error) { + func(ctx context.Context) (any, error) { tableList, err := c.db.Tables(ctx) if err != nil { return nil, err @@ -788,7 +788,7 @@ func (c *Core) IsSoftCreatedFieldName(fieldName string) bool { // FormatSqlBeforeExecuting formats the sql string and its arguments before executing. // The internal handleArguments function might be called twice during the SQL procedure, // but do not worry about it, it's safe and efficient. -func (c *Core) FormatSqlBeforeExecuting(sql string, args []interface{}) (newSql string, newArgs []interface{}) { +func (c *Core) FormatSqlBeforeExecuting(sql string, args []any) (newSql string, newArgs []any) { return handleSliceAndStructArgsForSql(sql, args) } diff --git a/database/gdb/gdb_core_structure.go b/database/gdb/gdb_core_structure.go index 05e09f02db9..65176aeebc3 100644 --- a/database/gdb/gdb_core_structure.go +++ b/database/gdb/gdb_core_structure.go @@ -70,7 +70,7 @@ func (c *Core) GetFieldType(ctx context.Context, fieldName, table, schema string // // The parameter `value` should be type of *map/map/*struct/struct. // It supports embedded struct definition for struct. -func (c *Core) ConvertDataForRecord(ctx context.Context, value interface{}, table string) (map[string]interface{}, error) { +func (c *Core) ConvertDataForRecord(ctx context.Context, value any, table string) (map[string]any, error) { var ( err error data = MapOrStructToMapDeep(value, true) @@ -92,7 +92,7 @@ func (c *Core) ConvertDataForRecord(ctx context.Context, value interface{}, tabl // ConvertValueForField converts value to the type of the record field. // The parameter `fieldType` is the target record field. // The parameter `fieldValue` is the value that to be committed to record field. -func (c *Core) ConvertValueForField(ctx context.Context, fieldType string, fieldValue interface{}) (interface{}, error) { +func (c *Core) ConvertValueForField(ctx context.Context, fieldType string, fieldValue any) (any, error) { var ( err error convertedValue = fieldValue @@ -114,7 +114,7 @@ Default: rvValue = reflect.ValueOf(fieldValue) rvKind = rvValue.Kind() ) - for rvKind == reflect.Ptr { + for rvKind == reflect.Pointer { rvValue = rvValue.Elem() rvKind = rvValue.Kind() } @@ -245,7 +245,7 @@ func (c *Core) GetFormattedDBTypeNameForField(fieldType string) (typeName, typeP // CheckLocalTypeForField checks and returns corresponding type for given db type. // The `fieldType` is retrieved from ColumnTypes of db driver, example: // UNSIGNED INT -func (c *Core) CheckLocalTypeForField(ctx context.Context, fieldType string, _ interface{}) (LocalType, error) { +func (c *Core) CheckLocalTypeForField(ctx context.Context, fieldType string, _ any) (LocalType, error) { var ( typeName string typePattern string @@ -379,10 +379,10 @@ func (c *Core) CheckLocalTypeForField(ctx context.Context, fieldType string, _ i // The parameter `fieldType` is in lower case, like: // `float(5,2)`, `unsigned double(5,2)`, `decimal(10,2)`, `char(45)`, `varchar(100)`, etc. func (c *Core) ConvertValueForLocal( - ctx context.Context, fieldType string, fieldValue interface{}, -) (interface{}, error) { + ctx context.Context, fieldType string, fieldValue any, +) (any, error) { // If there's no type retrieved, it returns the `fieldValue` directly - // to use its original data type, as `fieldValue` is type of interface{}. + // to use its original data type, as `fieldValue` is type of any. if fieldType == "" { return fieldValue, nil } @@ -471,7 +471,7 @@ func (c *Core) ConvertValueForLocal( // mappingAndFilterData automatically mappings the map key to table field and removes // all key-value pairs that are not the field of given table. -func (c *Core) mappingAndFilterData(ctx context.Context, schema, table string, data map[string]interface{}, filter bool) (map[string]interface{}, error) { +func (c *Core) mappingAndFilterData(ctx context.Context, schema, table string, data map[string]any, filter bool) (map[string]any, error) { fieldsMap, err := c.db.TableFields(ctx, c.guessPrimaryTableName(table), schema) if err != nil { return nil, err @@ -479,7 +479,7 @@ func (c *Core) mappingAndFilterData(ctx context.Context, schema, table string, d if len(fieldsMap) == 0 { return nil, gerror.Newf(`The table %s may not exist, or the table contains no fields`, table) } - fieldsKeyMap := make(map[string]interface{}, len(fieldsMap)) + fieldsKeyMap := make(map[string]any, len(fieldsMap)) for k := range fieldsMap { fieldsKeyMap[k] = nil } diff --git a/database/gdb/gdb_core_txcore.go b/database/gdb/gdb_core_txcore.go index 492d1338044..430d7e5b806 100644 --- a/database/gdb/gdb_core_txcore.go +++ b/database/gdb/gdb_core_txcore.go @@ -188,13 +188,13 @@ func (tx *TXCore) TransactionWithOptions( // Query does query operation on transaction. // See Core.Query. -func (tx *TXCore) Query(sql string, args ...interface{}) (result Result, err error) { +func (tx *TXCore) Query(sql string, args ...any) (result Result, err error) { return tx.db.DoQuery(tx.ctx, &txLink{tx.tx}, sql, args...) } // Exec does none query operation on transaction. // See Core.Exec. -func (tx *TXCore) Exec(sql string, args ...interface{}) (sql.Result, error) { +func (tx *TXCore) Exec(sql string, args ...any) (sql.Result, error) { return tx.db.DoExec(tx.ctx, &txLink{tx.tx}, sql, args...) } @@ -208,12 +208,12 @@ func (tx *TXCore) Prepare(sql string) (*Stmt, error) { } // GetAll queries and returns data records from database. -func (tx *TXCore) GetAll(sql string, args ...interface{}) (Result, error) { +func (tx *TXCore) GetAll(sql string, args ...any) (Result, error) { return tx.Query(sql, args...) } // GetOne queries and returns one record from database. -func (tx *TXCore) GetOne(sql string, args ...interface{}) (Record, error) { +func (tx *TXCore) GetOne(sql string, args ...any) (Record, error) { list, err := tx.GetAll(sql, args...) if err != nil { return nil, err @@ -226,7 +226,7 @@ func (tx *TXCore) GetOne(sql string, args ...interface{}) (Record, error) { // GetStruct queries one record from database and converts it to given struct. // The parameter `pointer` should be a pointer to struct. -func (tx *TXCore) GetStruct(obj interface{}, sql string, args ...interface{}) error { +func (tx *TXCore) GetStruct(obj any, sql string, args ...any) error { one, err := tx.GetOne(sql, args...) if err != nil { return err @@ -236,7 +236,7 @@ func (tx *TXCore) GetStruct(obj interface{}, sql string, args ...interface{}) er // GetStructs queries records from database and converts them to given struct. // The parameter `pointer` should be type of struct slice: []struct/[]*struct. -func (tx *TXCore) GetStructs(objPointerSlice interface{}, sql string, args ...interface{}) error { +func (tx *TXCore) GetStructs(objPointerSlice any, sql string, args ...any) error { all, err := tx.GetAll(sql, args...) if err != nil { return err @@ -250,9 +250,9 @@ func (tx *TXCore) GetStructs(objPointerSlice interface{}, sql string, args ...in // If parameter `pointer` is type of struct pointer, it calls GetStruct internally for // the conversion. If parameter `pointer` is type of slice, it calls GetStructs internally // for conversion. -func (tx *TXCore) GetScan(pointer interface{}, sql string, args ...interface{}) error { +func (tx *TXCore) GetScan(pointer any, sql string, args ...any) error { reflectInfo := reflection.OriginTypeAndKind(pointer) - if reflectInfo.InputKind != reflect.Ptr { + if reflectInfo.InputKind != reflect.Pointer { return gerror.NewCodef( gcode.CodeInvalidParameter, "params should be type of pointer, but got: %v", @@ -278,7 +278,7 @@ func (tx *TXCore) GetScan(pointer interface{}, sql string, args ...interface{}) // GetValue queries and returns the field value from database. // The sql should query only one field from database, or else it returns only one // field of the result. -func (tx *TXCore) GetValue(sql string, args ...interface{}) (Value, error) { +func (tx *TXCore) GetValue(sql string, args ...any) (Value, error) { one, err := tx.GetOne(sql, args...) if err != nil { return nil, err @@ -290,7 +290,7 @@ func (tx *TXCore) GetValue(sql string, args ...interface{}) (Value, error) { } // GetCount queries and returns the count from database. -func (tx *TXCore) GetCount(sql string, args ...interface{}) (int64, error) { +func (tx *TXCore) GetCount(sql string, args ...any) (int64, error) { if !gregex.IsMatchString(`(?i)SELECT\s+COUNT\(.+\)\s+FROM`, sql) { sql, _ = gregex.ReplaceString(`(?i)(SELECT)\s+(.+)\s+(FROM)`, `$1 COUNT($2) $3`, sql) } @@ -310,7 +310,7 @@ func (tx *TXCore) GetCount(sql string, args ...interface{}) (int64, error) { // Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}) // // The parameter `batch` specifies the batch operation count when given data is slice. -func (tx *TXCore) Insert(table string, data interface{}, batch ...int) (sql.Result, error) { +func (tx *TXCore) Insert(table string, data any, batch ...int) (sql.Result, error) { if len(batch) > 0 { return tx.Model(table).Ctx(tx.ctx).Data(data).Batch(batch[0]).Insert() } @@ -326,7 +326,7 @@ func (tx *TXCore) Insert(table string, data interface{}, batch ...int) (sql.Resu // Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}) // // The parameter `batch` specifies the batch operation count when given data is slice. -func (tx *TXCore) InsertIgnore(table string, data interface{}, batch ...int) (sql.Result, error) { +func (tx *TXCore) InsertIgnore(table string, data any, batch ...int) (sql.Result, error) { if len(batch) > 0 { return tx.Model(table).Ctx(tx.ctx).Data(data).Batch(batch[0]).InsertIgnore() } @@ -334,7 +334,7 @@ func (tx *TXCore) InsertIgnore(table string, data interface{}, batch ...int) (sq } // InsertAndGetId performs action Insert and returns the last insert id that automatically generated. -func (tx *TXCore) InsertAndGetId(table string, data interface{}, batch ...int) (int64, error) { +func (tx *TXCore) InsertAndGetId(table string, data any, batch ...int) (int64, error) { if len(batch) > 0 { return tx.Model(table).Ctx(tx.ctx).Data(data).Batch(batch[0]).InsertAndGetId() } @@ -353,7 +353,7 @@ func (tx *TXCore) InsertAndGetId(table string, data interface{}, batch ...int) ( // The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. // If given data is type of slice, it then does batch replacing, and the optional parameter // `batch` specifies the batch operation count. -func (tx *TXCore) Replace(table string, data interface{}, batch ...int) (sql.Result, error) { +func (tx *TXCore) Replace(table string, data any, batch ...int) (sql.Result, error) { if len(batch) > 0 { return tx.Model(table).Ctx(tx.ctx).Data(data).Batch(batch[0]).Replace() } @@ -371,7 +371,7 @@ func (tx *TXCore) Replace(table string, data interface{}, batch ...int) (sql.Res // // If given data is type of slice, it then does batch saving, and the optional parameter // `batch` specifies the batch operation count. -func (tx *TXCore) Save(table string, data interface{}, batch ...int) (sql.Result, error) { +func (tx *TXCore) Save(table string, data any, batch ...int) (sql.Result, error) { if len(batch) > 0 { return tx.Model(table).Ctx(tx.ctx).Data(data).Batch(batch[0]).Save() } @@ -392,7 +392,7 @@ func (tx *TXCore) Save(table string, data interface{}, batch ...int) (sql.Result // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 // User{ Id : 1, UserName : "john"}. -func (tx *TXCore) Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) { +func (tx *TXCore) Update(table string, data any, condition any, args ...any) (sql.Result, error) { return tx.Model(table).Ctx(tx.ctx).Data(data).Where(condition, args...).Update() } @@ -407,17 +407,17 @@ func (tx *TXCore) Update(table string, data interface{}, condition interface{}, // "status IN (?)", g.Slice{1,2,3} // "age IN(?,?)", 18, 50 // User{ Id : 1, UserName : "john"}. -func (tx *TXCore) Delete(table string, condition interface{}, args ...interface{}) (sql.Result, error) { +func (tx *TXCore) Delete(table string, condition any, args ...any) (sql.Result, error) { return tx.Model(table).Ctx(tx.ctx).Where(condition, args...).Delete() } // QueryContext implements interface function Link.QueryContext. -func (tx *TXCore) QueryContext(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error) { +func (tx *TXCore) QueryContext(ctx context.Context, sql string, args ...any) (*sql.Rows, error) { return tx.tx.QueryContext(ctx, sql, args...) } // ExecContext implements interface function Link.ExecContext. -func (tx *TXCore) ExecContext(ctx context.Context, sql string, args ...interface{}) (sql.Result, error) { +func (tx *TXCore) ExecContext(ctx context.Context, sql string, args ...any) (sql.Result, error) { return tx.tx.ExecContext(ctx, sql, args...) } diff --git a/database/gdb/gdb_core_underlying.go b/database/gdb/gdb_core_underlying.go index 7f06d4dfcad..7a3623c6215 100644 --- a/database/gdb/gdb_core_underlying.go +++ b/database/gdb/gdb_core_underlying.go @@ -28,13 +28,13 @@ import ( // Query commits one query SQL to underlying driver and returns the execution result. // It is most commonly used for data querying. -func (c *Core) Query(ctx context.Context, sql string, args ...interface{}) (result Result, err error) { +func (c *Core) Query(ctx context.Context, sql string, args ...any) (result Result, err error) { return c.db.DoQuery(ctx, nil, sql, args...) } // DoQuery commits the sql string and its arguments to underlying driver // through given link object and returns the execution result. -func (c *Core) DoQuery(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error) { +func (c *Core) DoQuery(ctx context.Context, link Link, sql string, args ...any) (result Result, err error) { // Transaction checks. if link == nil { if tx := TXFromCtx(ctx, c.db.GetGroup()); tx != nil { @@ -86,13 +86,13 @@ func (c *Core) DoQuery(ctx context.Context, link Link, sql string, args ...inter // Exec commits one query SQL to underlying driver and returns the execution result. // It is most commonly used for data inserting and updating. -func (c *Core) Exec(ctx context.Context, sql string, args ...interface{}) (result sql.Result, err error) { +func (c *Core) Exec(ctx context.Context, sql string, args ...any) (result sql.Result, err error) { return c.db.DoExec(ctx, nil, sql, args...) } // DoExec commits the sql string and its arguments to underlying driver // through given link object and returns the execution result. -func (c *Core) DoExec(ctx context.Context, link Link, sql string, args ...interface{}) (result sql.Result, err error) { +func (c *Core) DoExec(ctx context.Context, link Link, sql string, args ...any) (result sql.Result, err error) { // Transaction checks. if link == nil { if tx := TXFromCtx(ctx, c.db.GetGroup()); tx != nil { @@ -146,8 +146,8 @@ func (c *Core) DoExec(ctx context.Context, link Link, sql string, args ...interf // The parameter `link` specifies the current database connection operation object. You can modify the sql // string `sql` and its arguments `args` as you wish before they're committed to driver. func (c *Core) DoFilter( - ctx context.Context, link Link, sql string, args []interface{}, -) (newSql string, newArgs []interface{}, err error) { + ctx context.Context, link Link, sql string, args []any, +) (newSql string, newArgs []any, err error) { return sql, args, nil } @@ -460,9 +460,9 @@ func (c *Core) RowsToResult(ctx context.Context, rows *sql.Rows) (Result, error) } } var ( - values = make([]interface{}, len(columnTypes)) + values = make([]any, len(columnTypes)) result = make(Result, 0) - scanArgs = make([]interface{}, len(values)) + scanArgs = make([]any, len(values)) ) for i := range values { scanArgs[i] = &values[i] @@ -479,7 +479,7 @@ func (c *Core) RowsToResult(ctx context.Context, rows *sql.Rows) (Result, error) record[columnTypes[i].Name()] = nil } else { var ( - convertedValue interface{} + convertedValue any columnType = columnTypes[i] ) if convertedValue, err = c.columnValueToLocalValue(ctx, value, columnType); err != nil { @@ -502,8 +502,8 @@ func (c *Core) OrderRandomFunction() string { } func (c *Core) columnValueToLocalValue( - ctx context.Context, value interface{}, columnType *sql.ColumnType, -) (interface{}, error) { + ctx context.Context, value any, columnType *sql.ColumnType, +) (any, error) { var scanType = columnType.ScanType() if scanType != nil { // Common basic builtin types. diff --git a/database/gdb/gdb_driver_wrapper_db.go b/database/gdb/gdb_driver_wrapper_db.go index 4a6670627d7..7dbc1d0cee5 100644 --- a/database/gdb/gdb_driver_wrapper_db.go +++ b/database/gdb/gdb_driver_wrapper_db.go @@ -77,7 +77,7 @@ func (d *DriverWrapperDB) TableFields( gutil.GetOrDefaultStr(d.GetSchema(), schema...), table, ) - cacheFunc = func(ctx context.Context) (interface{}, error) { + cacheFunc = func(ctx context.Context) (any, error) { return d.DB.TableFields( context.WithValue(ctx, ctxKeyInternalProducedSQL, struct{}{}), table, schema..., diff --git a/database/gdb/gdb_func.go b/database/gdb/gdb_func.go index ba402e5c970..3bc40f590a8 100644 --- a/database/gdb/gdb_func.go +++ b/database/gdb/gdb_func.go @@ -40,12 +40,12 @@ type iString interface { // iIterator is the type assert api for Iterator. type iIterator interface { - Iterator(f func(key, value interface{}) bool) + Iterator(f func(key, value any) bool) } // iInterfaces is the type assert api for Interfaces. type iInterfaces interface { - Interfaces() []interface{} + Interfaces() []any } // iNil if the type assert api for IsNil. @@ -128,7 +128,7 @@ func CatchSQL(ctx context.Context, f func(ctx context.Context) error) (sqlArray } // isDoStruct checks and returns whether given type is a DO struct. -func isDoStruct(object interface{}) bool { +func isDoStruct(object any) bool { // It checks by struct name like "XxxForDao", to be compatible with old version. // TODO remove this compatible codes in future. reflectType := reflect.TypeOf(object) @@ -149,7 +149,7 @@ func isDoStruct(object interface{}) bool { } // getTableNameFromOrmTag retrieves and returns the table name from struct object. -func getTableNameFromOrmTag(object interface{}) string { +func getTableNameFromOrmTag(object any) string { var tableName string // Use the interface value. if r, ok := object.(iTableName); ok { @@ -185,13 +185,13 @@ func getTableNameFromOrmTag(object interface{}) string { // or else it returns an empty slice. // // The parameter `list` supports types like: -// []map[string]interface{} +// []map[string]any // []map[string]sub-map // []struct // []struct:sub-struct // Note that the sub-map/sub-struct makes sense only if the optional parameter `subKey` is given. // See gutil.ListItemValues. -func ListItemValues(list interface{}, key interface{}, subKey ...interface{}) (values []interface{}) { +func ListItemValues(list any, key any, subKey ...any) (values []any) { return gutil.ListItemValues(list, key, subKey...) } @@ -199,7 +199,7 @@ func ListItemValues(list interface{}, key interface{}, subKey ...interface{}) (v // Note that the parameter `list` should be type of slice which contains elements of map or struct, // or else it returns an empty slice. // See gutil.ListItemValuesUnique. -func ListItemValuesUnique(list interface{}, key string, subKey ...interface{}) []interface{} { +func ListItemValuesUnique(list any, key string, subKey ...any) []any { return gutil.ListItemValuesUnique(list, key, subKey...) } @@ -217,7 +217,7 @@ func GetInsertOperationByOption(option InsertOption) string { return operator } -func anyValueToMapBeforeToRecord(value interface{}) map[string]interface{} { +func anyValueToMapBeforeToRecord(value any) map[string]any { convertedMap := gconv.Map(value, gconv.MapOption{ Tags: structTagPriority, OmitEmpty: true, // To be compatible with old version from v2.6.0. @@ -253,7 +253,7 @@ func anyValueToMapBeforeToRecord(value interface{}) map[string]interface{} { // MapOrStructToMapDeep converts `value` to map type recursively(if attribute struct is embedded). // The parameter `value` should be type of *map/map/*struct/struct. // It supports embedded struct definition for struct. -func MapOrStructToMapDeep(value interface{}, omitempty bool) map[string]interface{} { +func MapOrStructToMapDeep(value any, omitempty bool) map[string]any { m := gconv.Map(value, gconv.MapOption{ Tags: structTagPriority, OmitEmpty: omitempty, @@ -379,7 +379,7 @@ func getFieldsFromStructOrMap(structOrMap any) (fields []any) { // // Note that it returns the given `where` parameter directly if the `primary` is empty // or length of `where` > 1. -func GetPrimaryKeyCondition(primary string, where ...interface{}) (newWhereCondition []interface{}) { +func GetPrimaryKeyCondition(primary string, where ...any) (newWhereCondition []any) { if len(where) == 0 { return nil } @@ -391,7 +391,7 @@ func GetPrimaryKeyCondition(primary string, where ...interface{}) (newWhereCondi rv = reflect.ValueOf(where[0]) kind = rv.Kind() ) - if kind == reflect.Ptr { + if kind == reflect.Pointer { rv = rv.Elem() kind = rv.Kind() } @@ -401,7 +401,7 @@ func GetPrimaryKeyCondition(primary string, where ...interface{}) (newWhereCondi break default: - return []interface{}{map[string]interface{}{ + return []any{map[string]any{ primary: where[0], }} } @@ -417,7 +417,7 @@ type formatWhereHolderInput struct { Table string // Table is used for fields mapping and filtering internally. } -func isKeyValueCanBeOmitEmpty(omitEmpty bool, whereType string, key, value interface{}) bool { +func isKeyValueCanBeOmitEmpty(omitEmpty bool, whereType string, key, value any) bool { if !omitEmpty { return false } @@ -443,7 +443,7 @@ func isKeyValueCanBeOmitEmpty(omitEmpty bool, whereType string, key, value inter } // formatWhereHolder formats where statement and its arguments for `Where` and `Having` statements. -func formatWhereHolder(ctx context.Context, db DB, in formatWhereHolderInput) (newWhere string, newArgs []interface{}) { +func formatWhereHolder(ctx context.Context, db DB, in formatWhereHolderInput) (newWhere string, newArgs []any) { var ( buffer = bytes.NewBuffer(nil) reflectInfo = reflection.OriginValueAndKind(in.Where) @@ -482,7 +482,7 @@ func formatWhereHolder(ctx context.Context, db DB, in formatWhereHolderInput) (n // For example, ListMap and TreeMap are ordered map, // which implement `iIterator` interface and are index-friendly for where conditions. if iterator, ok := in.Where.(iIterator); ok { - iterator.Iterator(func(key, value interface{}) bool { + iterator.Iterator(func(key, value any) bool { ketStr := gconv.String(key) if in.OmitNil && empty.IsNil(value) { return true @@ -559,7 +559,7 @@ func formatWhereHolder(ctx context.Context, db DB, in formatWhereHolderInput) (n default: // Where filter. - var omitEmptyCheckValue interface{} + var omitEmptyCheckValue any if len(in.Args) == 1 { omitEmptyCheckValue = in.Args[0] } else { @@ -665,8 +665,8 @@ func formatWhereHolder(ctx context.Context, db DB, in formatWhereHolderInput) (n return handleSliceAndStructArgsForSql(newWhere, newArgs) } -// formatWhereInterfaces formats `where` as []interface{}. -func formatWhereInterfaces(db DB, where []interface{}, buffer *bytes.Buffer, newArgs []interface{}) []interface{} { +// formatWhereInterfaces formats `where` as []any. +func formatWhereInterfaces(db DB, where []any, buffer *bytes.Buffer, newArgs []any) []any { if len(where) == 0 { return newArgs } @@ -694,16 +694,16 @@ func formatWhereInterfaces(db DB, where []interface{}, buffer *bytes.Buffer, new type formatWhereKeyValueInput struct { Db DB // Db is the underlying DB object for current operation. Buffer *bytes.Buffer // Buffer is the sql statement string without Args for current operation. - Args []interface{} // Args is the full arguments of current operation. + Args []any // Args is the full arguments of current operation. Key string // The field name, eg: "id", "name", etc. - Value interface{} // The field value, can be any types. + Value any // The field value, can be any types. Type string // The value in Where type. OmitEmpty bool // Ignores current condition key if `value` is empty. Prefix string // Field prefix, eg: "user", "order", etc. } // formatWhereKeyValue handles each key-value pair of the parameter map. -func formatWhereKeyValue(in formatWhereKeyValueInput) (newArgs []interface{}) { +func formatWhereKeyValue(in formatWhereKeyValueInput) (newArgs []any) { var ( quotedKey = in.Db.GetCore().QuoteWord(in.Key) holderCount = gstr.Count(quotedKey, "?") @@ -786,8 +786,8 @@ func formatWhereKeyValue(in formatWhereKeyValueInput) (newArgs []interface{}) { // handleSliceAndStructArgsForSql is an important function, which handles the sql and all its arguments // before committing them to underlying driver. func handleSliceAndStructArgsForSql( - oldSql string, oldArgs []interface{}, -) (newSql string, newArgs []interface{}) { + oldSql string, oldArgs []any, +) (newSql string, newArgs []any) { newSql = oldSql if len(oldArgs) == 0 { return @@ -817,9 +817,9 @@ func handleSliceAndStructArgsForSql( if gstr.Contains(newSql, "?") { whereKeyWord := " WHERE " if p := gstr.PosI(newSql, whereKeyWord); p == -1 { - return "0=1", []interface{}{} + return "0=1", []any{} } else { - return gstr.SubStr(newSql, 0, p+len(whereKeyWord)) + "0=1", []interface{}{} + return gstr.SubStr(newSql, 0, p+len(whereKeyWord)) + "0=1", []any{} } } } else { @@ -906,7 +906,7 @@ func handleSliceAndStructArgsForSql( // FormatSqlWithArgs binds the arguments to the sql string and returns a complete // sql string, just for debugging. -func FormatSqlWithArgs(sql string, args []interface{}) string { +func FormatSqlWithArgs(sql string, args []any) string { index := -1 newQuery, _ := gregex.ReplaceStringFunc( `(\?|:v\d+|\$\d+|@p\d+)`, @@ -922,7 +922,7 @@ func FormatSqlWithArgs(sql string, args []interface{}) string { return gconv.String(v) } reflectInfo := reflection.OriginValueAndKind(args[index]) - if reflectInfo.OriginKind == reflect.Ptr && + if reflectInfo.OriginKind == reflect.Pointer && (reflectInfo.OriginValue.IsNil() || !reflectInfo.OriginValue.IsValid()) { return "null" } @@ -968,7 +968,7 @@ func genTableFieldsCacheKey(group, schema, table string) string { ) } -func genSelectCacheKey(table, group, schema, name, sql string, args ...interface{}) string { +func genSelectCacheKey(table, group, schema, name, sql string, args ...any) string { if name == "" { name = fmt.Sprintf( `%s@%s#%s:%d`, diff --git a/database/gdb/gdb_model.go b/database/gdb/gdb_model.go index dc67fef7dfc..f02ab4c08f5 100644 --- a/database/gdb/gdb_model.go +++ b/database/gdb/gdb_model.go @@ -26,19 +26,19 @@ type Model struct { tables string // Operation table names, which can be more than one table names and aliases, like: "user", "user u", "user u, user_detail ud". fields []any // Operation fields, multiple fields joined using char ','. fieldsEx []any // Excluded operation fields, it here uses slice instead of string type for quick filtering. - withArray []interface{} // Arguments for With feature. + withArray []any // Arguments for With feature. withAll bool // Enable model association operations on all objects that have "with" tag in the struct. - extraArgs []interface{} // Extra custom arguments for sql, which are prepended to the arguments before sql committed to underlying driver. + extraArgs []any // Extra custom arguments for sql, which are prepended to the arguments before sql committed to underlying driver. whereBuilder *WhereBuilder // Condition builder for where operation. groupBy string // Used for "group by" statement. orderBy string // Used for "order by" statement. - having []interface{} // Used for "having..." statement. + having []any // Used for "having..." statement. start int // Used for "select ... start, limit ..." statement. limit int // Used for "select ... start, limit ..." statement. option int // Option for extra operation features. offset int // Offset statement for some databases grammar. partition string // Partition table partition name. - data interface{} // Data for operation, which can be type of map/[]map/struct/*struct/string, etc. + data any // Data for operation, which can be type of map/[]map/struct/*struct/string, etc. batch int // Batch number for batch Insert/Replace/Save operations. filter bool // Filter data and where key-value pairs according to the fields of the table. distinct string // Force the query to only return distinct results. @@ -48,9 +48,9 @@ type Model struct { hookHandler HookHandler // Hook functions for model hook feature. unscoped bool // Disables soft deleting features when select/delete operations. safe bool // If true, it clones and returns a new model object whenever operation done; or else it changes the attribute of current model. - onDuplicate interface{} // onDuplicate is used for on Upsert clause. - onDuplicateEx interface{} // onDuplicateEx is used for excluding some columns on Upsert clause. - onConflict interface{} // onConflict is used for conflict keys on Upsert clause. + onDuplicate any // onDuplicate is used for on Upsert clause. + onDuplicateEx any // onDuplicateEx is used for excluding some columns on Upsert clause. + onConflict any // onConflict is used for conflict keys on Upsert clause. tableAliasMap map[string]string // Table alias to true table name, usually used in join statements. softTimeOption SoftTimeOption // SoftTimeOption is the option to customize soft time feature for Model. shardingConfig ShardingConfig // ShardingConfig for database/table sharding feature. @@ -87,12 +87,12 @@ const ( // db.Model("user", "u") // 3. Model name with sub-query: // db.Model("? AS a, ? AS b", subQuery1, subQuery2) -func (c *Core) Model(tableNameQueryOrStruct ...interface{}) *Model { +func (c *Core) Model(tableNameQueryOrStruct ...any) *Model { var ( ctx = c.db.GetCtx() tableStr string tableName string - extraArgs []interface{} + extraArgs []any ) // Model creation with sub-query. if len(tableNameQueryOrStruct) > 1 { @@ -151,7 +151,7 @@ func (c *Core) Model(tableNameQueryOrStruct ...interface{}) *Model { // Example: // // db.Raw("SELECT * FROM `user` WHERE `name` = ?", "john").Scan(&result) -func (c *Core) Raw(rawSql string, args ...interface{}) *Model { +func (c *Core) Raw(rawSql string, args ...any) *Model { model := c.Model() model.rawSql = rawSql model.extraArgs = args @@ -164,19 +164,19 @@ func (c *Core) Raw(rawSql string, args ...interface{}) *Model { // db.Raw("SELECT * FROM `user` WHERE `name` = ?", "john").Scan(&result) // // See Core.Raw. -func (m *Model) Raw(rawSql string, args ...interface{}) *Model { +func (m *Model) Raw(rawSql string, args ...any) *Model { model := m.db.Raw(rawSql, args...) model.db = m.db model.tx = m.tx return model } -func (tx *TXCore) Raw(rawSql string, args ...interface{}) *Model { +func (tx *TXCore) Raw(rawSql string, args ...any) *Model { return tx.Model().Raw(rawSql, args...) } // With creates and returns an ORM model based on metadata of given object. -func (c *Core) With(objects ...interface{}) *Model { +func (c *Core) With(objects ...any) *Model { return c.db.Model().With(objects...) } @@ -191,7 +191,7 @@ func (m *Model) Partition(partitions ...string) *Model { // Model acts like Core.Model except it operates on transaction. // See Core.Model. -func (tx *TXCore) Model(tableNameQueryOrStruct ...interface{}) *Model { +func (tx *TXCore) Model(tableNameQueryOrStruct ...any) *Model { model := tx.db.Model(tableNameQueryOrStruct...) model.db = tx.db model.tx = tx @@ -200,7 +200,7 @@ func (tx *TXCore) Model(tableNameQueryOrStruct ...interface{}) *Model { // With acts like Core.With except it operates on transaction. // See Core.With. -func (tx *TXCore) With(object interface{}) *Model { +func (tx *TXCore) With(object any) *Model { return tx.Model().With(object) } @@ -291,15 +291,15 @@ func (m *Model) Clone() *Model { copy(newModel.fieldsEx, m.fieldsEx) } if n := len(m.extraArgs); n > 0 { - newModel.extraArgs = make([]interface{}, n) + newModel.extraArgs = make([]any, n) copy(newModel.extraArgs, m.extraArgs) } if n := len(m.withArray); n > 0 { - newModel.withArray = make([]interface{}, n) + newModel.withArray = make([]any, n) copy(newModel.withArray, m.withArray) } if n := len(m.having); n > 0 { - newModel.having = make([]interface{}, n) + newModel.having = make([]any, n) copy(newModel.having, m.having) } return newModel @@ -332,7 +332,7 @@ func (m *Model) Safe(safe ...bool) *Model { } // Args sets custom arguments for model operation. -func (m *Model) Args(args ...interface{}) *Model { +func (m *Model) Args(args ...any) *Model { model := m.getModel() model.extraArgs = append(model.extraArgs, args) return model diff --git a/database/gdb/gdb_model_builder.go b/database/gdb/gdb_model_builder.go index 3b378dcafd8..d775a52bfeb 100644 --- a/database/gdb/gdb_model_builder.go +++ b/database/gdb/gdb_model_builder.go @@ -18,11 +18,11 @@ type WhereBuilder struct { // WhereHolder is the holder for where condition preparing. type WhereHolder struct { - Type string // Type of this holder. - Operator int // Operator for this holder. - Where interface{} // Where parameter, which can commonly be type of string/map/struct. - Args []interface{} // Arguments for where parameter. - Prefix string // Field prefix, eg: "user.", "order.". + Type string // Type of this holder. + Operator int // Operator for this holder. + Where any // Where parameter, which can commonly be type of string/map/struct. + Args []any // Arguments for where parameter. + Prefix string // Field prefix, eg: "user.", "order.". } // Builder creates and returns a WhereBuilder. Please note that the builder is chain-safe. @@ -48,7 +48,7 @@ func (b *WhereBuilder) Clone() *WhereBuilder { } // Build builds current WhereBuilder and returns the condition string and parameters. -func (b *WhereBuilder) Build() (conditionWhere string, conditionArgs []interface{}) { +func (b *WhereBuilder) Build() (conditionWhere string, conditionArgs []any) { var ( ctx = b.model.GetCtx() autoPrefix = b.model.getAutoPrefix() @@ -104,7 +104,7 @@ func (b *WhereBuilder) Build() (conditionWhere string, conditionArgs []interface } // convertWhereBuilder converts parameter `where` to condition string and parameters if `where` is also a WhereBuilder. -func (b *WhereBuilder) convertWhereBuilder(where interface{}, args []interface{}) (newWhere interface{}, newArgs []interface{}) { +func (b *WhereBuilder) convertWhereBuilder(where any, args []any) (newWhere any, newArgs []any) { var builder *WhereBuilder switch v := where.(type) { case WhereBuilder: diff --git a/database/gdb/gdb_model_builder_where.go b/database/gdb/gdb_model_builder_where.go index 7b695b96b64..581bdec3bae 100644 --- a/database/gdb/gdb_model_builder_where.go +++ b/database/gdb/gdb_model_builder_where.go @@ -15,7 +15,7 @@ import ( // doWhereType sets the condition statement for the model. The parameter `where` can be type of // string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times, // multiple conditions will be joined into where statement using "AND". -func (b *WhereBuilder) doWhereType(whereType string, where interface{}, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) doWhereType(whereType string, where any, args ...any) *WhereBuilder { where, args = b.convertWhereBuilder(where, args) builder := b.getBuilder() @@ -41,7 +41,7 @@ func (b *WhereBuilder) doWhereType(whereType string, where interface{}, args ... // doWherefType builds condition string using fmt.Sprintf and arguments. // Note that if the number of `args` is more than the placeholder in `format`, // the extra `args` will be used as the where condition arguments of the Model. -func (b *WhereBuilder) doWherefType(t string, format string, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) doWherefType(t string, format string, args ...any) *WhereBuilder { var ( placeHolderCount = gstr.Count(format, "?") conditionStr = fmt.Sprintf(format, args[:len(args)-placeHolderCount]...) @@ -60,7 +60,7 @@ func (b *WhereBuilder) doWherefType(t string, format string, args ...interface{} // Where("status IN (?)", g.Slice{1,2,3}) // Where("age IN(?,?)", 18, 50) // Where(User{ Id : 1, UserName : "john"}). -func (b *WhereBuilder) Where(where interface{}, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) Where(where any, args ...any) *WhereBuilder { return b.doWhereType(``, where, args...) } @@ -70,7 +70,7 @@ func (b *WhereBuilder) Where(where interface{}, args ...interface{}) *WhereBuild // Eg: // Wheref(`amount WHERE `amount`<100 and status='paid' // Wheref(`amount<%d and status=%s`, 100, "paid") => WHERE `amount`<100 and status='paid' -func (b *WhereBuilder) Wheref(format string, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) Wheref(format string, args ...any) *WhereBuilder { return b.doWherefType(``, format, args...) } @@ -79,7 +79,7 @@ func (b *WhereBuilder) Wheref(format string, args ...interface{}) *WhereBuilder // key value. That is, if primary key is "id" and given `where` parameter as "123", the // WherePri function treats the condition as "id=123", but Model.Where treats the condition // as string "123". -func (b *WhereBuilder) WherePri(where interface{}, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePri(where any, args ...any) *WhereBuilder { if len(args) > 0 { return b.Where(where, args...) } @@ -88,27 +88,27 @@ func (b *WhereBuilder) WherePri(where interface{}, args ...interface{}) *WhereBu } // WhereLT builds `column < value` statement. -func (b *WhereBuilder) WhereLT(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereLT(column string, value any) *WhereBuilder { return b.Wheref(`%s < ?`, b.model.QuoteWord(column), value) } // WhereLTE builds `column <= value` statement. -func (b *WhereBuilder) WhereLTE(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereLTE(column string, value any) *WhereBuilder { return b.Wheref(`%s <= ?`, b.model.QuoteWord(column), value) } // WhereGT builds `column > value` statement. -func (b *WhereBuilder) WhereGT(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereGT(column string, value any) *WhereBuilder { return b.Wheref(`%s > ?`, b.model.QuoteWord(column), value) } // WhereGTE builds `column >= value` statement. -func (b *WhereBuilder) WhereGTE(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereGTE(column string, value any) *WhereBuilder { return b.Wheref(`%s >= ?`, b.model.QuoteWord(column), value) } // WhereBetween builds `column BETWEEN min AND max` statement. -func (b *WhereBuilder) WhereBetween(column string, min, max interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereBetween(column string, min, max any) *WhereBuilder { return b.Wheref(`%s BETWEEN ? AND ?`, b.model.QuoteWord(column), min, max) } @@ -118,7 +118,7 @@ func (b *WhereBuilder) WhereLike(column string, like string) *WhereBuilder { } // WhereIn builds `column IN (in)` statement. -func (b *WhereBuilder) WhereIn(column string, in interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereIn(column string, in any) *WhereBuilder { return b.doWherefType(whereHolderTypeIn, `%s IN (?)`, b.model.QuoteWord(column), in) } @@ -132,22 +132,22 @@ func (b *WhereBuilder) WhereNull(columns ...string) *WhereBuilder { } // WhereNotBetween builds `column NOT BETWEEN min AND max` statement. -func (b *WhereBuilder) WhereNotBetween(column string, min, max interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereNotBetween(column string, min, max any) *WhereBuilder { return b.Wheref(`%s NOT BETWEEN ? AND ?`, b.model.QuoteWord(column), min, max) } // WhereNotLike builds `column NOT LIKE like` statement. -func (b *WhereBuilder) WhereNotLike(column string, like interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereNotLike(column string, like any) *WhereBuilder { return b.Wheref(`%s NOT LIKE ?`, b.model.QuoteWord(column), like) } // WhereNot builds `column != value` statement. -func (b *WhereBuilder) WhereNot(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereNot(column string, value any) *WhereBuilder { return b.Wheref(`%s != ?`, b.model.QuoteWord(column), value) } // WhereNotIn builds `column NOT IN (in)` statement. -func (b *WhereBuilder) WhereNotIn(column string, in interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereNotIn(column string, in any) *WhereBuilder { return b.doWherefType(whereHolderTypeIn, `%s NOT IN (?)`, b.model.QuoteWord(column), in) } diff --git a/database/gdb/gdb_model_builder_where_prefix.go b/database/gdb/gdb_model_builder_where_prefix.go index eec46db1d00..67ebc254c52 100644 --- a/database/gdb/gdb_model_builder_where_prefix.go +++ b/database/gdb/gdb_model_builder_where_prefix.go @@ -10,7 +10,7 @@ package gdb // Eg: // WherePrefix("order", "status", "paid") => WHERE `order`.`status`='paid' // WherePrefix("order", struct{Status:"paid", "channel":"bank"}) => WHERE `order`.`status`='paid' AND `order`.`channel`='bank' -func (b *WhereBuilder) WherePrefix(prefix string, where interface{}, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefix(prefix string, where any, args ...any) *WhereBuilder { where, args = b.convertWhereBuilder(where, args) builder := b.getBuilder() @@ -28,37 +28,37 @@ func (b *WhereBuilder) WherePrefix(prefix string, where interface{}, args ...int } // WherePrefixLT builds `prefix.column < value` statement. -func (b *WhereBuilder) WherePrefixLT(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixLT(prefix string, column string, value any) *WhereBuilder { return b.Wheref(`%s.%s < ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WherePrefixLTE builds `prefix.column <= value` statement. -func (b *WhereBuilder) WherePrefixLTE(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixLTE(prefix string, column string, value any) *WhereBuilder { return b.Wheref(`%s.%s <= ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WherePrefixGT builds `prefix.column > value` statement. -func (b *WhereBuilder) WherePrefixGT(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixGT(prefix string, column string, value any) *WhereBuilder { return b.Wheref(`%s.%s > ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WherePrefixGTE builds `prefix.column >= value` statement. -func (b *WhereBuilder) WherePrefixGTE(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixGTE(prefix string, column string, value any) *WhereBuilder { return b.Wheref(`%s.%s >= ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WherePrefixBetween builds `prefix.column BETWEEN min AND max` statement. -func (b *WhereBuilder) WherePrefixBetween(prefix string, column string, min, max interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixBetween(prefix string, column string, min, max any) *WhereBuilder { return b.Wheref(`%s.%s BETWEEN ? AND ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), min, max) } // WherePrefixLike builds `prefix.column LIKE like` statement. -func (b *WhereBuilder) WherePrefixLike(prefix string, column string, like interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixLike(prefix string, column string, like any) *WhereBuilder { return b.Wheref(`%s.%s LIKE ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), like) } // WherePrefixIn builds `prefix.column IN (in)` statement. -func (b *WhereBuilder) WherePrefixIn(prefix string, column string, in interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixIn(prefix string, column string, in any) *WhereBuilder { return b.doWherefType(whereHolderTypeIn, `%s.%s IN (?)`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), in) } @@ -72,22 +72,22 @@ func (b *WhereBuilder) WherePrefixNull(prefix string, columns ...string) *WhereB } // WherePrefixNotBetween builds `prefix.column NOT BETWEEN min AND max` statement. -func (b *WhereBuilder) WherePrefixNotBetween(prefix string, column string, min, max interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixNotBetween(prefix string, column string, min, max any) *WhereBuilder { return b.Wheref(`%s.%s NOT BETWEEN ? AND ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), min, max) } // WherePrefixNotLike builds `prefix.column NOT LIKE like` statement. -func (b *WhereBuilder) WherePrefixNotLike(prefix string, column string, like interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixNotLike(prefix string, column string, like any) *WhereBuilder { return b.Wheref(`%s.%s NOT LIKE ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), like) } // WherePrefixNot builds `prefix.column != value` statement. -func (b *WhereBuilder) WherePrefixNot(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixNot(prefix string, column string, value any) *WhereBuilder { return b.Wheref(`%s.%s != ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WherePrefixNotIn builds `prefix.column NOT IN (in)` statement. -func (b *WhereBuilder) WherePrefixNotIn(prefix string, column string, in interface{}) *WhereBuilder { +func (b *WhereBuilder) WherePrefixNotIn(prefix string, column string, in any) *WhereBuilder { return b.doWherefType(whereHolderTypeIn, `%s.%s NOT IN (?)`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), in) } diff --git a/database/gdb/gdb_model_builder_whereor.go b/database/gdb/gdb_model_builder_whereor.go index 3a83593b934..33d32f1382b 100644 --- a/database/gdb/gdb_model_builder_whereor.go +++ b/database/gdb/gdb_model_builder_whereor.go @@ -13,7 +13,7 @@ import ( ) // WhereOr adds "OR" condition to the where statement. -func (b *WhereBuilder) doWhereOrType(t string, where interface{}, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) doWhereOrType(t string, where any, args ...any) *WhereBuilder { where, args = b.convertWhereBuilder(where, args) builder := b.getBuilder() @@ -30,7 +30,7 @@ func (b *WhereBuilder) doWhereOrType(t string, where interface{}, args ...interf } // WhereOrf builds `OR` condition string using fmt.Sprintf and arguments. -func (b *WhereBuilder) doWhereOrfType(t string, format string, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) doWhereOrfType(t string, format string, args ...any) *WhereBuilder { var ( placeHolderCount = gstr.Count(format, "?") conditionStr = fmt.Sprintf(format, args[:len(args)-placeHolderCount]...) @@ -39,7 +39,7 @@ func (b *WhereBuilder) doWhereOrfType(t string, format string, args ...interface } // WhereOr adds "OR" condition to the where statement. -func (b *WhereBuilder) WhereOr(where interface{}, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOr(where any, args ...any) *WhereBuilder { return b.doWhereOrType(``, where, args...) } @@ -47,47 +47,47 @@ func (b *WhereBuilder) WhereOr(where interface{}, args ...interface{}) *WhereBui // Eg: // WhereOrf(`amount WHERE xxx OR `amount`<100 and status='paid' // WhereOrf(`amount<%d and status=%s`, 100, "paid") => WHERE xxx OR `amount`<100 and status='paid' -func (b *WhereBuilder) WhereOrf(format string, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrf(format string, args ...any) *WhereBuilder { return b.doWhereOrfType(``, format, args...) } // WhereOrNot builds `column != value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrNot(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrNot(column string, value any) *WhereBuilder { return b.WhereOrf(`%s != ?`, column, value) } // WhereOrLT builds `column < value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrLT(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrLT(column string, value any) *WhereBuilder { return b.WhereOrf(`%s < ?`, column, value) } // WhereOrLTE builds `column <= value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrLTE(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrLTE(column string, value any) *WhereBuilder { return b.WhereOrf(`%s <= ?`, column, value) } // WhereOrGT builds `column > value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrGT(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrGT(column string, value any) *WhereBuilder { return b.WhereOrf(`%s > ?`, column, value) } // WhereOrGTE builds `column >= value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrGTE(column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrGTE(column string, value any) *WhereBuilder { return b.WhereOrf(`%s >= ?`, column, value) } // WhereOrBetween builds `column BETWEEN min AND max` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrBetween(column string, min, max interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrBetween(column string, min, max any) *WhereBuilder { return b.WhereOrf(`%s BETWEEN ? AND ?`, b.model.QuoteWord(column), min, max) } // WhereOrLike builds `column LIKE 'like'` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrLike(column string, like interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrLike(column string, like any) *WhereBuilder { return b.WhereOrf(`%s LIKE ?`, b.model.QuoteWord(column), like) } // WhereOrIn builds `column IN (in)` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrIn(column string, in interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrIn(column string, in any) *WhereBuilder { return b.doWhereOrfType(whereHolderTypeIn, `%s IN (?)`, b.model.QuoteWord(column), in) } @@ -101,17 +101,17 @@ func (b *WhereBuilder) WhereOrNull(columns ...string) *WhereBuilder { } // WhereOrNotBetween builds `column NOT BETWEEN min AND max` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrNotBetween(column string, min, max interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrNotBetween(column string, min, max any) *WhereBuilder { return b.WhereOrf(`%s NOT BETWEEN ? AND ?`, b.model.QuoteWord(column), min, max) } // WhereOrNotLike builds `column NOT LIKE like` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrNotLike(column string, like interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrNotLike(column string, like any) *WhereBuilder { return b.WhereOrf(`%s NOT LIKE ?`, b.model.QuoteWord(column), like) } // WhereOrNotIn builds `column NOT IN (in)` statement. -func (b *WhereBuilder) WhereOrNotIn(column string, in interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrNotIn(column string, in any) *WhereBuilder { return b.doWhereOrfType(whereHolderTypeIn, `%s NOT IN (?)`, b.model.QuoteWord(column), in) } diff --git a/database/gdb/gdb_model_builder_whereor_prefix.go b/database/gdb/gdb_model_builder_whereor_prefix.go index cb272fee651..8707584049b 100644 --- a/database/gdb/gdb_model_builder_whereor_prefix.go +++ b/database/gdb/gdb_model_builder_whereor_prefix.go @@ -10,7 +10,7 @@ package gdb // Eg: // WhereOrPrefix("order", "status", "paid") => WHERE xxx OR (`order`.`status`='paid') // WhereOrPrefix("order", struct{Status:"paid", "channel":"bank"}) => WHERE xxx OR (`order`.`status`='paid' AND `order`.`channel`='bank') -func (b *WhereBuilder) WhereOrPrefix(prefix string, where interface{}, args ...interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefix(prefix string, where any, args ...any) *WhereBuilder { where, args = b.convertWhereBuilder(where, args) builder := b.getBuilder() @@ -25,42 +25,42 @@ func (b *WhereBuilder) WhereOrPrefix(prefix string, where interface{}, args ...i } // WhereOrPrefixNot builds `prefix.column != value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixNot(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixNot(prefix string, column string, value any) *WhereBuilder { return b.WhereOrf(`%s.%s != ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WhereOrPrefixLT builds `prefix.column < value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixLT(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixLT(prefix string, column string, value any) *WhereBuilder { return b.WhereOrf(`%s.%s < ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WhereOrPrefixLTE builds `prefix.column <= value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixLTE(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixLTE(prefix string, column string, value any) *WhereBuilder { return b.WhereOrf(`%s.%s <= ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WhereOrPrefixGT builds `prefix.column > value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixGT(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixGT(prefix string, column string, value any) *WhereBuilder { return b.WhereOrf(`%s.%s > ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WhereOrPrefixGTE builds `prefix.column >= value` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixGTE(prefix string, column string, value interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixGTE(prefix string, column string, value any) *WhereBuilder { return b.WhereOrf(`%s.%s >= ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), value) } // WhereOrPrefixBetween builds `prefix.column BETWEEN min AND max` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixBetween(prefix string, column string, min, max interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixBetween(prefix string, column string, min, max any) *WhereBuilder { return b.WhereOrf(`%s.%s BETWEEN ? AND ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), min, max) } // WhereOrPrefixLike builds `prefix.column LIKE 'like'` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixLike(prefix string, column string, like interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixLike(prefix string, column string, like any) *WhereBuilder { return b.WhereOrf(`%s.%s LIKE ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), like) } // WhereOrPrefixIn builds `prefix.column IN (in)` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixIn(prefix string, column string, in interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixIn(prefix string, column string, in any) *WhereBuilder { return b.doWhereOrfType(whereHolderTypeIn, `%s.%s IN (?)`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), in) } @@ -74,17 +74,17 @@ func (b *WhereBuilder) WhereOrPrefixNull(prefix string, columns ...string) *Wher } // WhereOrPrefixNotBetween builds `prefix.column NOT BETWEEN min AND max` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixNotBetween(prefix string, column string, min, max interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixNotBetween(prefix string, column string, min, max any) *WhereBuilder { return b.WhereOrf(`%s.%s NOT BETWEEN ? AND ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), min, max) } // WhereOrPrefixNotLike builds `prefix.column NOT LIKE 'like'` statement in `OR` conditions. -func (b *WhereBuilder) WhereOrPrefixNotLike(prefix string, column string, like interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixNotLike(prefix string, column string, like any) *WhereBuilder { return b.WhereOrf(`%s.%s NOT LIKE ?`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), like) } // WhereOrPrefixNotIn builds `prefix.column NOT IN (in)` statement. -func (b *WhereBuilder) WhereOrPrefixNotIn(prefix string, column string, in interface{}) *WhereBuilder { +func (b *WhereBuilder) WhereOrPrefixNotIn(prefix string, column string, in any) *WhereBuilder { return b.doWhereOrfType(whereHolderTypeIn, `%s.%s NOT IN (?)`, b.model.QuoteWord(prefix), b.model.QuoteWord(column), in) } diff --git a/database/gdb/gdb_model_cache.go b/database/gdb/gdb_model_cache.go index 76592cdec29..dd7dac7fa4e 100644 --- a/database/gdb/gdb_model_cache.go +++ b/database/gdb/gdb_model_cache.go @@ -61,7 +61,7 @@ func (m *Model) checkAndRemoveSelectCache(ctx context.Context) { } } -func (m *Model) getSelectResultFromCache(ctx context.Context, sql string, args ...interface{}) (result Result, err error) { +func (m *Model) getSelectResultFromCache(ctx context.Context, sql string, args ...any) (result Result, err error) { if !m.cacheEnabled || m.tx != nil { return } @@ -90,7 +90,7 @@ func (m *Model) getSelectResultFromCache(ctx context.Context, sql string, args . } func (m *Model) saveSelectResultToCache( - ctx context.Context, selectType SelectType, result Result, sql string, args ...interface{}, + ctx context.Context, selectType SelectType, result Result, sql string, args ...any, ) (err error) { if !m.cacheEnabled || m.tx != nil { return @@ -142,7 +142,7 @@ func (m *Model) saveSelectResultToCache( return } -func (m *Model) makeSelectCacheKey(sql string, args ...interface{}) string { +func (m *Model) makeSelectCacheKey(sql string, args ...any) string { var ( table = m.db.GetCore().guessPrimaryTableName(m.tables) group = m.db.GetGroup() diff --git a/database/gdb/gdb_model_delete.go b/database/gdb/gdb_model_delete.go index 25b417be59e..f8811c086aa 100644 --- a/database/gdb/gdb_model_delete.go +++ b/database/gdb/gdb_model_delete.go @@ -18,7 +18,7 @@ import ( // Delete does "DELETE FROM ... " statement for the model. // The optional parameter `where` is the same as the parameter of Model.Where function, // see Model.Where. -func (m *Model) Delete(where ...interface{}) (result sql.Result, err error) { +func (m *Model) Delete(where ...any) (result sql.Result, err error) { var ctx = m.GetCtx() if len(where) > 0 { return m.Where(where[0], where[1:]...).Delete() @@ -67,7 +67,7 @@ func (m *Model) Delete(where ...interface{}) (result sql.Result, err error) { Schema: m.schema, Data: dataHolder, Condition: conditionStr, - Args: append([]interface{}{dataValue}, conditionArgs...), + Args: append([]any{dataValue}, conditionArgs...), } return in.Next(ctx) } diff --git a/database/gdb/gdb_model_fields.go b/database/gdb/gdb_model_fields.go index 9f7e2cc7c51..04ad3638ea1 100644 --- a/database/gdb/gdb_model_fields.go +++ b/database/gdb/gdb_model_fields.go @@ -21,9 +21,9 @@ import ( // Example: // Fields("id", "name", "age") // Fields([]string{"id", "name", "age"}) -// Fields(map[string]interface{}{"id":1, "name":"john", "age":18}) +// Fields(map[string]any{"id":1, "name":"john", "age":18}) // Fields(User{Id: 1, Name: "john", Age: 18}). -func (m *Model) Fields(fieldNamesOrMapStruct ...interface{}) *Model { +func (m *Model) Fields(fieldNamesOrMapStruct ...any) *Model { length := len(fieldNamesOrMapStruct) if length == 0 { return m @@ -37,7 +37,7 @@ func (m *Model) Fields(fieldNamesOrMapStruct ...interface{}) *Model { } // FieldsPrefix performs as function Fields but add extra prefix for each field. -func (m *Model) FieldsPrefix(prefixOrAlias string, fieldNamesOrMapStruct ...interface{}) *Model { +func (m *Model) FieldsPrefix(prefixOrAlias string, fieldNamesOrMapStruct ...any) *Model { fields := m.filterFieldsFrom( m.getTableNameByPrefixOrAlias(prefixOrAlias), fieldNamesOrMapStruct..., @@ -60,13 +60,13 @@ func (m *Model) FieldsPrefix(prefixOrAlias string, fieldNamesOrMapStruct ...inte // Example: // FieldsEx("id", "name", "age") // FieldsEx([]string{"id", "name", "age"}) -// FieldsEx(map[string]interface{}{"id":1, "name":"john", "age":18}) +// FieldsEx(map[string]any{"id":1, "name":"john", "age":18}) // FieldsEx(User{Id: 1, Name: "john", Age: 18}). -func (m *Model) FieldsEx(fieldNamesOrMapStruct ...interface{}) *Model { +func (m *Model) FieldsEx(fieldNamesOrMapStruct ...any) *Model { return m.doFieldsEx(m.tablesInit, fieldNamesOrMapStruct...) } -func (m *Model) doFieldsEx(table string, fieldNamesOrMapStruct ...interface{}) *Model { +func (m *Model) doFieldsEx(table string, fieldNamesOrMapStruct ...any) *Model { length := len(fieldNamesOrMapStruct) if length == 0 { return m @@ -81,7 +81,7 @@ func (m *Model) doFieldsEx(table string, fieldNamesOrMapStruct ...interface{}) * } // FieldsExPrefix performs as function FieldsEx but add extra prefix for each field. -func (m *Model) FieldsExPrefix(prefixOrAlias string, fieldNamesOrMapStruct ...interface{}) *Model { +func (m *Model) FieldsExPrefix(prefixOrAlias string, fieldNamesOrMapStruct ...any) *Model { model := m.doFieldsEx( m.getTableNameByPrefixOrAlias(prefixOrAlias), fieldNamesOrMapStruct..., diff --git a/database/gdb/gdb_model_hook.go b/database/gdb/gdb_model_hook.go index 7c88428f7dc..50987884134 100644 --- a/database/gdb/gdb_model_hook.go +++ b/database/gdb/gdb_model_hook.go @@ -66,12 +66,12 @@ type internalParamHookDelete struct { // which is usually not be interesting for upper business hook handler. type HookSelectInput struct { internalParamHookSelect - Model *Model // Current operation Model. - Table string // The table name that to be used. Update this attribute to change target table name. - Schema string // The schema name that to be used. Update this attribute to change target schema name. - Sql string // The sql string that to be committed. - Args []interface{} // The arguments of sql. - SelectType SelectType // The type of this SELECT operation. + Model *Model // Current operation Model. + Table string // The table name that to be used. Update this attribute to change target table name. + Schema string // The schema name that to be used. Update this attribute to change target schema name. + Sql string // The sql string that to be committed. + Args []any // The arguments of sql. + SelectType SelectType // The type of this SELECT operation. } // HookInsertInput holds the parameters for insert hook operation. @@ -87,22 +87,22 @@ type HookInsertInput struct { // HookUpdateInput holds the parameters for update hook operation. type HookUpdateInput struct { internalParamHookUpdate - Model *Model // Current operation Model. - Table string // The table name that to be used. Update this attribute to change target table name. - Schema string // The schema name that to be used. Update this attribute to change target schema name. - Data interface{} // Data can be type of: map[string]interface{}/string. You can use type assertion on `Data`. - Condition string // The where condition string for updating. - Args []interface{} // The arguments for sql place-holders. + Model *Model // Current operation Model. + Table string // The table name that to be used. Update this attribute to change target table name. + Schema string // The schema name that to be used. Update this attribute to change target schema name. + Data any // Data can be type of: map[string]any/string. You can use type assertion on `Data`. + Condition string // The where condition string for updating. + Args []any // The arguments for sql place-holders. } // HookDeleteInput holds the parameters for delete hook operation. type HookDeleteInput struct { internalParamHookDelete - Model *Model // Current operation Model. - Table string // The table name that to be used. Update this attribute to change target table name. - Schema string // The schema name that to be used. Update this attribute to change target schema name. - Condition string // The where condition string for deleting. - Args []interface{} // The arguments for sql place-holders. + Model *Model // Current operation Model. + Table string // The table name that to be used. Update this attribute to change target table name. + Schema string // The schema name that to be used. Update this attribute to change target schema name. + Condition string // The where condition string for deleting. + Args []any // The arguments for sql place-holders. } const ( diff --git a/database/gdb/gdb_model_insert.go b/database/gdb/gdb_model_insert.go index efb65df06c2..a322d75f43f 100644 --- a/database/gdb/gdb_model_insert.go +++ b/database/gdb/gdb_model_insert.go @@ -38,14 +38,14 @@ func (m *Model) Batch(batch int) *Model { // Data("uid=? AND name=?", 10000, "john") // Data(g.Map{"uid": 10000, "name":"john"}) // Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}). -func (m *Model) Data(data ...interface{}) *Model { +func (m *Model) Data(data ...any) *Model { var model = m.getModel() if len(data) > 1 { if s := gconv.String(data[0]); gstr.Contains(s, "?") { model.data = s model.extraArgs = data[1:] } else { - newData := make(map[string]interface{}) + newData := make(map[string]any) for i := 0; i < len(data); i += 2 { newData[gconv.String(data[i])] = data[i+1] } @@ -121,7 +121,7 @@ func (m *Model) Data(data ...interface{}) *Model { // OnConflict sets the primary key or index when columns conflicts occurs. // It's not necessary for MySQL driver. -func (m *Model) OnConflict(onConflict ...interface{}) *Model { +func (m *Model) OnConflict(onConflict ...any) *Model { if len(onConflict) == 0 { return m } @@ -150,7 +150,7 @@ func (m *Model) OnConflict(onConflict ...interface{}) *Model { // OnDuplicate(g.Map{ // "nickname": "passport", // }). -func (m *Model) OnDuplicate(onDuplicate ...interface{}) *Model { +func (m *Model) OnDuplicate(onDuplicate ...any) *Model { if len(onDuplicate) == 0 { return m } @@ -176,7 +176,7 @@ func (m *Model) OnDuplicate(onDuplicate ...interface{}) *Model { // "passport": "", // "password": "", // }). -func (m *Model) OnDuplicateEx(onDuplicateEx ...interface{}) *Model { +func (m *Model) OnDuplicateEx(onDuplicateEx ...any) *Model { if len(onDuplicateEx) == 0 { return m } @@ -192,7 +192,7 @@ func (m *Model) OnDuplicateEx(onDuplicateEx ...interface{}) *Model { // Insert does "INSERT INTO ..." statement for the model. // The optional parameter `data` is the same as the parameter of Model.Data function, // see Model.Data. -func (m *Model) Insert(data ...interface{}) (result sql.Result, err error) { +func (m *Model) Insert(data ...any) (result sql.Result, err error) { var ctx = m.GetCtx() if len(data) > 0 { return m.Data(data...).Insert() @@ -201,7 +201,7 @@ func (m *Model) Insert(data ...interface{}) (result sql.Result, err error) { } // InsertAndGetId performs action Insert and returns the last insert id that automatically generated. -func (m *Model) InsertAndGetId(data ...interface{}) (lastInsertId int64, err error) { +func (m *Model) InsertAndGetId(data ...any) (lastInsertId int64, err error) { var ctx = m.GetCtx() if len(data) > 0 { return m.Data(data...).InsertAndGetId() @@ -216,7 +216,7 @@ func (m *Model) InsertAndGetId(data ...interface{}) (lastInsertId int64, err err // InsertIgnore does "INSERT IGNORE INTO ..." statement for the model. // The optional parameter `data` is the same as the parameter of Model.Data function, // see Model.Data. -func (m *Model) InsertIgnore(data ...interface{}) (result sql.Result, err error) { +func (m *Model) InsertIgnore(data ...any) (result sql.Result, err error) { var ctx = m.GetCtx() if len(data) > 0 { return m.Data(data...).InsertIgnore() @@ -227,7 +227,7 @@ func (m *Model) InsertIgnore(data ...interface{}) (result sql.Result, err error) // Replace does "REPLACE INTO ..." statement for the model. // The optional parameter `data` is the same as the parameter of Model.Data function, // see Model.Data. -func (m *Model) Replace(data ...interface{}) (result sql.Result, err error) { +func (m *Model) Replace(data ...any) (result sql.Result, err error) { var ctx = m.GetCtx() if len(data) > 0 { return m.Data(data...).Replace() @@ -241,7 +241,7 @@ func (m *Model) Replace(data ...interface{}) (result sql.Result, err error) { // // It updates the record if there's primary or unique index in the saving data, // or else it inserts a new record into the table. -func (m *Model) Save(data ...interface{}) (result sql.Result, err error) { +func (m *Model) Save(data ...any) (result sql.Result, err error) { var ctx = m.GetCtx() if len(data) > 0 { return m.Data(data...).Save() @@ -371,7 +371,7 @@ func (m *Model) formatDoInsertOption(insertOption InsertOption, columnNames []st reflectInfo := reflection.OriginValueAndKind(m.onDuplicate) switch reflectInfo.OriginKind { case reflect.String: - option.OnDuplicateMap = make(map[string]interface{}) + option.OnDuplicateMap = make(map[string]any) for _, v := range gstr.SplitAndTrim(reflectInfo.OriginValue.String(), ",") { if onDuplicateExKeySet.Contains(v) { continue @@ -380,7 +380,7 @@ func (m *Model) formatDoInsertOption(insertOption InsertOption, columnNames []st } case reflect.Map: - option.OnDuplicateMap = make(map[string]interface{}) + option.OnDuplicateMap = make(map[string]any) for k, v := range gconv.Map(m.onDuplicate) { if onDuplicateExKeySet.Contains(k) { continue @@ -389,7 +389,7 @@ func (m *Model) formatDoInsertOption(insertOption InsertOption, columnNames []st } case reflect.Slice, reflect.Array: - option.OnDuplicateMap = make(map[string]interface{}) + option.OnDuplicateMap = make(map[string]any) for _, v := range gconv.Strings(m.onDuplicate) { if onDuplicateExKeySet.Contains(v) { continue @@ -406,7 +406,7 @@ func (m *Model) formatDoInsertOption(insertOption InsertOption, columnNames []st } } } else if onDuplicateExKeySet.Size() > 0 { - option.OnDuplicateMap = make(map[string]interface{}) + option.OnDuplicateMap = make(map[string]any) for _, v := range columnNames { if onDuplicateExKeySet.Contains(v) { continue @@ -417,7 +417,7 @@ func (m *Model) formatDoInsertOption(insertOption InsertOption, columnNames []st return } -func (m *Model) formatOnDuplicateExKeys(onDuplicateEx interface{}) ([]string, error) { +func (m *Model) formatOnDuplicateExKeys(onDuplicateEx any) ([]string, error) { if onDuplicateEx == nil { return nil, nil } @@ -442,7 +442,7 @@ func (m *Model) formatOnDuplicateExKeys(onDuplicateEx interface{}) ([]string, er } } -func (m *Model) formatOnConflictKeys(onConflict interface{}) ([]string, error) { +func (m *Model) formatOnConflictKeys(onConflict any) ([]string, error) { if onConflict == nil { return nil, nil } diff --git a/database/gdb/gdb_model_order_group.go b/database/gdb/gdb_model_order_group.go index 664dcf540a9..ee502cd5b5b 100644 --- a/database/gdb/gdb_model_order_group.go +++ b/database/gdb/gdb_model_order_group.go @@ -22,7 +22,7 @@ import ( // Order("id desc", "name asc") // Order("id desc").Order("name asc") // Order(gdb.Raw("field(id, 3,1,2)")). -func (m *Model) Order(orderBy ...interface{}) *Model { +func (m *Model) Order(orderBy ...any) *Model { if len(orderBy) == 0 { return m } diff --git a/database/gdb/gdb_model_select.go b/database/gdb/gdb_model_select.go index cc7a08148e4..27b18d5e4ec 100644 --- a/database/gdb/gdb_model_select.go +++ b/database/gdb/gdb_model_select.go @@ -26,7 +26,7 @@ import ( // // The optional parameter `where` is the same as the parameter of Model.Where function, // see Model.Where. -func (m *Model) All(where ...interface{}) (Result, error) { +func (m *Model) All(where ...any) (Result, error) { var ctx = m.GetCtx() return m.doGetAll(ctx, SelectTypeDefault, false, where...) } @@ -42,7 +42,7 @@ func (m *Model) All(where ...interface{}) (Result, error) { // var model Model // var result Result // var count int -// where := []interface{}{"name = ?", "John"} +// where := []any{"name = ?", "John"} // result, count, err := model.AllAndCount(true) // if err != nil { // // Handle error. @@ -105,7 +105,7 @@ func (m *Model) Chunk(size int, handler ChunkHandler) { // // The optional parameter `where` is the same as the parameter of Model.Where function, // see Model.Where. -func (m *Model) One(where ...interface{}) (Record, error) { +func (m *Model) One(where ...any) (Record, error) { var ctx = m.GetCtx() if len(where) > 0 { return m.Where(where[0], where[1:]...).One() @@ -126,7 +126,7 @@ func (m *Model) One(where ...interface{}) (Record, error) { // If the optional parameter `fieldsAndWhere` is given, the fieldsAndWhere[0] is the selected fields // and fieldsAndWhere[1:] is treated as where condition fields. // Also see Model.Fields and Model.Where functions. -func (m *Model) Array(fieldsAndWhere ...interface{}) ([]Value, error) { +func (m *Model) Array(fieldsAndWhere ...any) ([]Value, error) { if len(fieldsAndWhere) > 0 { if len(fieldsAndWhere) > 2 { return m.Fields(gconv.String(fieldsAndWhere[0])).Where(fieldsAndWhere[1], fieldsAndWhere[2:]...).Array() @@ -192,7 +192,7 @@ func (m *Model) Array(fieldsAndWhere ...interface{}) ([]Value, error) { // // user := (*User)(nil) // err := db.Model("user").Where("id", 1).Scan(&user). -func (m *Model) doStruct(pointer interface{}, where ...interface{}) error { +func (m *Model) doStruct(pointer any, where ...any) error { model := m // Auto selecting fields by struct attributes. if len(model.fieldsEx) == 0 && len(model.fields) == 0 { @@ -228,7 +228,7 @@ func (m *Model) doStruct(pointer interface{}, where ...interface{}) error { // // users := ([]*User)(nil) // err := db.Model("user").Scan(&users). -func (m *Model) doStructs(pointer interface{}, where ...interface{}) error { +func (m *Model) doStructs(pointer any, where ...any) error { model := m // Auto selecting fields by struct attributes. if len(model.fieldsEx) == 0 && len(model.fields) == 0 { @@ -277,9 +277,9 @@ func (m *Model) doStructs(pointer interface{}, where ...interface{}) error { // // users := ([]*User)(nil) // err := db.Model("user").Scan(&users). -func (m *Model) Scan(pointer interface{}, where ...interface{}) error { +func (m *Model) Scan(pointer any, where ...any) error { reflectInfo := reflection.OriginTypeAndKind(pointer) - if reflectInfo.InputKind != reflect.Ptr { + if reflectInfo.InputKind != reflect.Pointer { return gerror.NewCode( gcode.CodeInvalidParameter, `the parameter "pointer" for function Scan should type of pointer`, @@ -330,7 +330,7 @@ func (m *Model) Scan(pointer interface{}, where ...interface{}) error { // Fields("u1.passport,u1.id,u2.name,u2.age"). // Where("u1.id<2"). // ScanAndCount(&users, &count, false) -func (m *Model) ScanAndCount(pointer interface{}, totalCount *int, useFieldForCount bool) (err error) { +func (m *Model) ScanAndCount(pointer any, totalCount *int, useFieldForCount bool) (err error) { // support Fields with *, example: .Fields("a.*, b.name"). Count sql is select count(1) from xxx countModel := m.Clone() // If useFieldForCount is false, set the fields to a constant value of 1 for counting @@ -356,7 +356,7 @@ func (m *Model) ScanAndCount(pointer interface{}, totalCount *int, useFieldForCo // Note that the parameter `listPointer` should be type of *[]struct/*[]*struct. // // See Result.ScanList. -func (m *Model) ScanList(structSlicePointer interface{}, bindToAttrName string, relationAttrNameAndFields ...string) (err error) { +func (m *Model) ScanList(structSlicePointer any, bindToAttrName string, relationAttrNameAndFields ...string) (err error) { var result Result out, err := checkGetSliceElementInfoForScanList(structSlicePointer, bindToAttrName) if err != nil { @@ -400,7 +400,7 @@ func (m *Model) ScanList(structSlicePointer interface{}, bindToAttrName string, // If the optional parameter `fieldsAndWhere` is given, the fieldsAndWhere[0] is the selected fields // and fieldsAndWhere[1:] is treated as where condition fields. // Also see Model.Fields and Model.Where functions. -func (m *Model) Value(fieldsAndWhere ...interface{}) (Value, error) { +func (m *Model) Value(fieldsAndWhere ...any) (Value, error) { var ( core = m.db.GetCore() ctx = core.injectInternalColumn(m.GetCtx()) @@ -466,7 +466,7 @@ func (m *Model) getRecordFields(record Record) []string { // Count does "SELECT COUNT(x) FROM ..." statement for the model. // The optional parameter `where` is the same as the parameter of Model.Where function, // see Model.Where. -func (m *Model) Count(where ...interface{}) (int, error) { +func (m *Model) Count(where ...any) (int, error) { var ( core = m.db.GetCore() ctx = core.injectInternalColumn(m.GetCtx()) @@ -515,7 +515,7 @@ func (m *Model) Count(where ...interface{}) (int, error) { // Exist does "SELECT 1 FROM ... LIMIT 1" statement for the model. // The optional parameter `where` is the same as the parameter of Model.Where function, // see Model.Where. -func (m *Model) Exist(where ...interface{}) (bool, error) { +func (m *Model) Exist(where ...any) (bool, error) { if len(where) > 0 { return m.Where(where[0], where[1:]...).Exist() } @@ -644,9 +644,9 @@ func (m *Model) Page(page, limit int) *Model { // Having sets the having statement for the model. // The parameters of this function usage are as the same as function Where. // See Where. -func (m *Model) Having(having interface{}, args ...interface{}) *Model { +func (m *Model) Having(having any, args ...any) *Model { model := m.getModel() - model.having = []interface{}{ + model.having = []any{ having, args, } return model @@ -659,7 +659,7 @@ func (m *Model) Having(having interface{}, args ...interface{}) *Model { // The parameter `limit1` specifies whether limits querying only one record if m.limit is not set. // The optional parameter `where` is the same as the parameter of Model.Where function, // see Model.Where. -func (m *Model) doGetAll(ctx context.Context, selectType SelectType, limit1 bool, where ...interface{}) (Result, error) { +func (m *Model) doGetAll(ctx context.Context, selectType SelectType, limit1 bool, where ...any) (Result, error) { if len(where) > 0 { return m.Where(where[0], where[1:]...).All() } @@ -669,7 +669,7 @@ func (m *Model) doGetAll(ctx context.Context, selectType SelectType, limit1 bool // doGetAllBySql does the select statement on the database. func (m *Model) doGetAllBySql( - ctx context.Context, selectType SelectType, sql string, args ...interface{}, + ctx context.Context, selectType SelectType, sql string, args ...any, ) (result Result, err error) { if result, err = m.getSelectResultFromCache(ctx, sql, args...); err != nil || result != nil { return @@ -699,7 +699,7 @@ func (m *Model) doGetAllBySql( func (m *Model) getFormattedSqlAndArgs( ctx context.Context, selectType SelectType, limit1 bool, -) (sqlWithHolder string, holderArgs []interface{}) { +) (sqlWithHolder string, holderArgs []any) { switch selectType { case SelectTypeCount: queryFields := "COUNT(1)" @@ -741,7 +741,7 @@ func (m *Model) getFormattedSqlAndArgs( } } -func (m *Model) getHolderAndArgsAsSubModel(ctx context.Context) (holder string, args []interface{}) { +func (m *Model) getHolderAndArgsAsSubModel(ctx context.Context) (holder string, args []any) { holder, args = m.getFormattedSqlAndArgs( ctx, SelectTypeDefault, false, ) @@ -840,7 +840,7 @@ func (m *Model) getFieldsFiltered() string { // The parameter `limit1` specifies whether limits querying only one record if m.limit is not set. func (m *Model) formatCondition( ctx context.Context, limit1 bool, isCountStatement bool, -) (conditionWhere string, conditionExtra string, conditionArgs []interface{}) { +) (conditionWhere string, conditionExtra string, conditionArgs []any) { var autoPrefix = m.getAutoPrefix() // GROUP BY. if m.groupBy != "" { diff --git a/database/gdb/gdb_model_soft_time.go b/database/gdb/gdb_model_soft_time.go index 73e155275c8..3972bf64787 100644 --- a/database/gdb/gdb_model_soft_time.go +++ b/database/gdb/gdb_model_soft_time.go @@ -195,7 +195,7 @@ func (m *softTimeMaintainer) getSoftFieldNameAndType( schema, table, strings.Join(checkFiledNames, "_"), ) cacheDuration = gcache.DurationNoExpire - cacheFunc = func(ctx context.Context) (value interface{}, err error) { + cacheFunc = func(ctx context.Context) (value any, err error) { // Ignore the error from TableFields. fieldsMap, err := m.TableFields(table, schema) if err != nil { diff --git a/database/gdb/gdb_model_update.go b/database/gdb/gdb_model_update.go index c253ab96d28..05e430b1386 100644 --- a/database/gdb/gdb_model_update.go +++ b/database/gdb/gdb_model_update.go @@ -25,7 +25,7 @@ import ( // If the optional parameter `dataAndWhere` is given, the dataAndWhere[0] is the updated data field, // and dataAndWhere[1:] is treated as where condition fields. // Also see Model.Data and Model.Where functions. -func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err error) { +func (m *Model) Update(dataAndWhere ...any) (result sql.Result, err error) { var ctx = m.GetCtx() if len(dataAndWhere) > 0 { if len(dataAndWhere) > 2 { @@ -45,7 +45,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro return nil, gerror.NewCode(gcode.CodeMissingParameter, "updating table with empty data") } var ( - newData interface{} + newData any stm = m.softTimeMaintainer() reflectInfo = reflection.OriginTypeAndKind(m.data) conditionWhere, conditionExtra, conditionArgs = m.formatCondition(ctx, false, false) @@ -79,7 +79,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro if fieldNameUpdate != "" && !gstr.Contains(updateStr, fieldNameUpdate) { dataValue := stm.GetValueByFieldTypeForCreateOrUpdate(ctx, fieldTypeUpdate, false) updateStr += fmt.Sprintf(`,%s=?`, fieldNameUpdate) - conditionArgs = append([]interface{}{dataValue}, conditionArgs...) + conditionArgs = append([]any{dataValue}, conditionArgs...) } newData = updateStr } @@ -114,7 +114,7 @@ func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err erro } // UpdateAndGetAffected performs update statement and returns the affected rows number. -func (m *Model) UpdateAndGetAffected(dataAndWhere ...interface{}) (affected int64, err error) { +func (m *Model) UpdateAndGetAffected(dataAndWhere ...any) (affected int64, err error) { result, err := m.Update(dataAndWhere...) if err != nil { return 0, err @@ -124,7 +124,7 @@ func (m *Model) UpdateAndGetAffected(dataAndWhere ...interface{}) (affected int6 // Increment increments a column's value by a given amount. // The parameter `amount` can be type of float or integer. -func (m *Model) Increment(column string, amount interface{}) (sql.Result, error) { +func (m *Model) Increment(column string, amount any) (sql.Result, error) { return m.getModel().Data(column, &Counter{ Field: column, Value: gconv.Float64(amount), @@ -133,7 +133,7 @@ func (m *Model) Increment(column string, amount interface{}) (sql.Result, error) // Decrement decrements a column's value by a given amount. // The parameter `amount` can be type of float or integer. -func (m *Model) Decrement(column string, amount interface{}) (sql.Result, error) { +func (m *Model) Decrement(column string, amount any) (sql.Result, error) { return m.getModel().Data(column, &Counter{ Field: column, Value: -gconv.Float64(amount), diff --git a/database/gdb/gdb_model_utility.go b/database/gdb/gdb_model_utility.go index b9782f7fa11..4da7dc69eee 100644 --- a/database/gdb/gdb_model_utility.go +++ b/database/gdb/gdb_model_utility.go @@ -80,7 +80,7 @@ func (m *Model) mappingAndFilterToTableFields(table string, fields []any, filter return fields } var outputFieldsArray = make([]any, 0) - fieldsKeyMap := make(map[string]interface{}, len(fieldsMap)) + fieldsKeyMap := make(map[string]any, len(fieldsMap)) for k := range fieldsMap { fieldsKeyMap[k] = nil } @@ -126,7 +126,7 @@ func (m *Model) mappingAndFilterToTableFields(table string, fields []any, filter // filterDataForInsertOrUpdate does filter feature with data for inserting/updating operations. // Note that, it does not filter list item, which is also type of map, for "omit empty" feature. -func (m *Model) filterDataForInsertOrUpdate(data interface{}) (interface{}, error) { +func (m *Model) filterDataForInsertOrUpdate(data any) (any, error) { var err error switch value := data.(type) { case List: @@ -294,9 +294,9 @@ func (m *Model) getPrimaryKey() string { } // mergeArguments creates and returns new arguments by merging `m.extraArgs` and given `args`. -func (m *Model) mergeArguments(args []interface{}) []interface{} { +func (m *Model) mergeArguments(args []any) []any { if len(m.extraArgs) > 0 { - newArgs := make([]interface{}, len(m.extraArgs)+len(args)) + newArgs := make([]any, len(m.extraArgs)+len(args)) copy(newArgs, m.extraArgs) copy(newArgs[len(m.extraArgs):], args) return newArgs diff --git a/database/gdb/gdb_model_where.go b/database/gdb/gdb_model_where.go index 067a9bcadb9..c22b794ac6a 100644 --- a/database/gdb/gdb_model_where.go +++ b/database/gdb/gdb_model_where.go @@ -18,7 +18,7 @@ func (m *Model) callWhereBuilder(builder *WhereBuilder) *Model { // string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times, // multiple conditions will be joined into where statement using "AND". // See WhereBuilder.Where. -func (m *Model) Where(where interface{}, args ...interface{}) *Model { +func (m *Model) Where(where any, args ...any) *Model { return m.callWhereBuilder(m.whereBuilder.Where(where, args...)) } @@ -26,7 +26,7 @@ func (m *Model) Where(where interface{}, args ...interface{}) *Model { // Note that if the number of `args` is more than the placeholder in `format`, // the extra `args` will be used as the where condition arguments of the Model. // See WhereBuilder.Wheref. -func (m *Model) Wheref(format string, args ...interface{}) *Model { +func (m *Model) Wheref(format string, args ...any) *Model { return m.callWhereBuilder(m.whereBuilder.Wheref(format, args...)) } @@ -36,37 +36,37 @@ func (m *Model) Wheref(format string, args ...interface{}) *Model { // WherePri function treats the condition as "id=123", but Model.Where treats the condition // as string "123". // See WhereBuilder.WherePri. -func (m *Model) WherePri(where interface{}, args ...interface{}) *Model { +func (m *Model) WherePri(where any, args ...any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePri(where, args...)) } // WhereLT builds `column < value` statement. // See WhereBuilder.WhereLT. -func (m *Model) WhereLT(column string, value interface{}) *Model { +func (m *Model) WhereLT(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereLT(column, value)) } // WhereLTE builds `column <= value` statement. // See WhereBuilder.WhereLTE. -func (m *Model) WhereLTE(column string, value interface{}) *Model { +func (m *Model) WhereLTE(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereLTE(column, value)) } // WhereGT builds `column > value` statement. // See WhereBuilder.WhereGT. -func (m *Model) WhereGT(column string, value interface{}) *Model { +func (m *Model) WhereGT(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereGT(column, value)) } // WhereGTE builds `column >= value` statement. // See WhereBuilder.WhereGTE. -func (m *Model) WhereGTE(column string, value interface{}) *Model { +func (m *Model) WhereGTE(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereGTE(column, value)) } // WhereBetween builds `column BETWEEN min AND max` statement. // See WhereBuilder.WhereBetween. -func (m *Model) WhereBetween(column string, min, max interface{}) *Model { +func (m *Model) WhereBetween(column string, min, max any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereBetween(column, min, max)) } @@ -78,7 +78,7 @@ func (m *Model) WhereLike(column string, like string) *Model { // WhereIn builds `column IN (in)` statement. // See WhereBuilder.WhereIn. -func (m *Model) WhereIn(column string, in interface{}) *Model { +func (m *Model) WhereIn(column string, in any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereIn(column, in)) } @@ -90,25 +90,25 @@ func (m *Model) WhereNull(columns ...string) *Model { // WhereNotBetween builds `column NOT BETWEEN min AND max` statement. // See WhereBuilder.WhereNotBetween. -func (m *Model) WhereNotBetween(column string, min, max interface{}) *Model { +func (m *Model) WhereNotBetween(column string, min, max any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereNotBetween(column, min, max)) } // WhereNotLike builds `column NOT LIKE like` statement. // See WhereBuilder.WhereNotLike. -func (m *Model) WhereNotLike(column string, like interface{}) *Model { +func (m *Model) WhereNotLike(column string, like any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereNotLike(column, like)) } // WhereNot builds `column != value` statement. // See WhereBuilder.WhereNot. -func (m *Model) WhereNot(column string, value interface{}) *Model { +func (m *Model) WhereNot(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereNot(column, value)) } // WhereNotIn builds `column NOT IN (in)` statement. // See WhereBuilder.WhereNotIn. -func (m *Model) WhereNotIn(column string, in interface{}) *Model { +func (m *Model) WhereNotIn(column string, in any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereNotIn(column, in)) } diff --git a/database/gdb/gdb_model_where_prefix.go b/database/gdb/gdb_model_where_prefix.go index 079052f983c..b68e50401d2 100644 --- a/database/gdb/gdb_model_where_prefix.go +++ b/database/gdb/gdb_model_where_prefix.go @@ -8,49 +8,49 @@ package gdb // WherePrefix performs as Where, but it adds prefix to each field in where statement. // See WhereBuilder.WherePrefix. -func (m *Model) WherePrefix(prefix string, where interface{}, args ...interface{}) *Model { +func (m *Model) WherePrefix(prefix string, where any, args ...any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefix(prefix, where, args...)) } // WherePrefixLT builds `prefix.column < value` statement. // See WhereBuilder.WherePrefixLT. -func (m *Model) WherePrefixLT(prefix string, column string, value interface{}) *Model { +func (m *Model) WherePrefixLT(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixLT(prefix, column, value)) } // WherePrefixLTE builds `prefix.column <= value` statement. // See WhereBuilder.WherePrefixLTE. -func (m *Model) WherePrefixLTE(prefix string, column string, value interface{}) *Model { +func (m *Model) WherePrefixLTE(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixLTE(prefix, column, value)) } // WherePrefixGT builds `prefix.column > value` statement. // See WhereBuilder.WherePrefixGT. -func (m *Model) WherePrefixGT(prefix string, column string, value interface{}) *Model { +func (m *Model) WherePrefixGT(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixGT(prefix, column, value)) } // WherePrefixGTE builds `prefix.column >= value` statement. // See WhereBuilder.WherePrefixGTE. -func (m *Model) WherePrefixGTE(prefix string, column string, value interface{}) *Model { +func (m *Model) WherePrefixGTE(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixGTE(prefix, column, value)) } // WherePrefixBetween builds `prefix.column BETWEEN min AND max` statement. // See WhereBuilder.WherePrefixBetween. -func (m *Model) WherePrefixBetween(prefix string, column string, min, max interface{}) *Model { +func (m *Model) WherePrefixBetween(prefix string, column string, min, max any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixBetween(prefix, column, min, max)) } // WherePrefixLike builds `prefix.column LIKE like` statement. // See WhereBuilder.WherePrefixLike. -func (m *Model) WherePrefixLike(prefix string, column string, like interface{}) *Model { +func (m *Model) WherePrefixLike(prefix string, column string, like any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixLike(prefix, column, like)) } // WherePrefixIn builds `prefix.column IN (in)` statement. // See WhereBuilder.WherePrefixIn. -func (m *Model) WherePrefixIn(prefix string, column string, in interface{}) *Model { +func (m *Model) WherePrefixIn(prefix string, column string, in any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixIn(prefix, column, in)) } @@ -62,25 +62,25 @@ func (m *Model) WherePrefixNull(prefix string, columns ...string) *Model { // WherePrefixNotBetween builds `prefix.column NOT BETWEEN min AND max` statement. // See WhereBuilder.WherePrefixNotBetween. -func (m *Model) WherePrefixNotBetween(prefix string, column string, min, max interface{}) *Model { +func (m *Model) WherePrefixNotBetween(prefix string, column string, min, max any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixNotBetween(prefix, column, min, max)) } // WherePrefixNotLike builds `prefix.column NOT LIKE like` statement. // See WhereBuilder.WherePrefixNotLike. -func (m *Model) WherePrefixNotLike(prefix string, column string, like interface{}) *Model { +func (m *Model) WherePrefixNotLike(prefix string, column string, like any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixNotLike(prefix, column, like)) } // WherePrefixNot builds `prefix.column != value` statement. // See WhereBuilder.WherePrefixNot. -func (m *Model) WherePrefixNot(prefix string, column string, value interface{}) *Model { +func (m *Model) WherePrefixNot(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixNot(prefix, column, value)) } // WherePrefixNotIn builds `prefix.column NOT IN (in)` statement. // See WhereBuilder.WherePrefixNotIn. -func (m *Model) WherePrefixNotIn(prefix string, column string, in interface{}) *Model { +func (m *Model) WherePrefixNotIn(prefix string, column string, in any) *Model { return m.callWhereBuilder(m.whereBuilder.WherePrefixNotIn(prefix, column, in)) } diff --git a/database/gdb/gdb_model_whereor.go b/database/gdb/gdb_model_whereor.go index e699d2de5ef..725f54740fe 100644 --- a/database/gdb/gdb_model_whereor.go +++ b/database/gdb/gdb_model_whereor.go @@ -8,55 +8,55 @@ package gdb // WhereOr adds "OR" condition to the where statement. // See WhereBuilder.WhereOr. -func (m *Model) WhereOr(where interface{}, args ...interface{}) *Model { +func (m *Model) WhereOr(where any, args ...any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOr(where, args...)) } // WhereOrf builds `OR` condition string using fmt.Sprintf and arguments. // See WhereBuilder.WhereOrf. -func (m *Model) WhereOrf(format string, args ...interface{}) *Model { +func (m *Model) WhereOrf(format string, args ...any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrf(format, args...)) } // WhereOrLT builds `column < value` statement in `OR` conditions. // See WhereBuilder.WhereOrLT. -func (m *Model) WhereOrLT(column string, value interface{}) *Model { +func (m *Model) WhereOrLT(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrLT(column, value)) } // WhereOrLTE builds `column <= value` statement in `OR` conditions. // See WhereBuilder.WhereOrLTE. -func (m *Model) WhereOrLTE(column string, value interface{}) *Model { +func (m *Model) WhereOrLTE(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrLTE(column, value)) } // WhereOrGT builds `column > value` statement in `OR` conditions. // See WhereBuilder.WhereOrGT. -func (m *Model) WhereOrGT(column string, value interface{}) *Model { +func (m *Model) WhereOrGT(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrGT(column, value)) } // WhereOrGTE builds `column >= value` statement in `OR` conditions. // See WhereBuilder.WhereOrGTE. -func (m *Model) WhereOrGTE(column string, value interface{}) *Model { +func (m *Model) WhereOrGTE(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrGTE(column, value)) } // WhereOrBetween builds `column BETWEEN min AND max` statement in `OR` conditions. // See WhereBuilder.WhereOrBetween. -func (m *Model) WhereOrBetween(column string, min, max interface{}) *Model { +func (m *Model) WhereOrBetween(column string, min, max any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrBetween(column, min, max)) } // WhereOrLike builds `column LIKE like` statement in `OR` conditions. // See WhereBuilder.WhereOrLike. -func (m *Model) WhereOrLike(column string, like interface{}) *Model { +func (m *Model) WhereOrLike(column string, like any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrLike(column, like)) } // WhereOrIn builds `column IN (in)` statement in `OR` conditions. // See WhereBuilder.WhereOrIn. -func (m *Model) WhereOrIn(column string, in interface{}) *Model { +func (m *Model) WhereOrIn(column string, in any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrIn(column, in)) } @@ -68,25 +68,25 @@ func (m *Model) WhereOrNull(columns ...string) *Model { // WhereOrNotBetween builds `column NOT BETWEEN min AND max` statement in `OR` conditions. // See WhereBuilder.WhereOrNotBetween. -func (m *Model) WhereOrNotBetween(column string, min, max interface{}) *Model { +func (m *Model) WhereOrNotBetween(column string, min, max any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrNotBetween(column, min, max)) } // WhereOrNotLike builds `column NOT LIKE 'like'` statement in `OR` conditions. // See WhereBuilder.WhereOrNotLike. -func (m *Model) WhereOrNotLike(column string, like interface{}) *Model { +func (m *Model) WhereOrNotLike(column string, like any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrNotLike(column, like)) } // WhereOrNot builds `column != value` statement. // See WhereBuilder.WhereOrNot. -func (m *Model) WhereOrNot(column string, value interface{}) *Model { +func (m *Model) WhereOrNot(column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrNot(column, value)) } // WhereOrNotIn builds `column NOT IN (in)` statement. // See WhereBuilder.WhereOrNotIn. -func (m *Model) WhereOrNotIn(column string, in interface{}) *Model { +func (m *Model) WhereOrNotIn(column string, in any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrNotIn(column, in)) } diff --git a/database/gdb/gdb_model_whereor_prefix.go b/database/gdb/gdb_model_whereor_prefix.go index fd917b8fc25..5b2adb46d76 100644 --- a/database/gdb/gdb_model_whereor_prefix.go +++ b/database/gdb/gdb_model_whereor_prefix.go @@ -8,49 +8,49 @@ package gdb // WhereOrPrefix performs as WhereOr, but it adds prefix to each field in where statement. // See WhereBuilder.WhereOrPrefix. -func (m *Model) WhereOrPrefix(prefix string, where interface{}, args ...interface{}) *Model { +func (m *Model) WhereOrPrefix(prefix string, where any, args ...any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefix(prefix, where, args...)) } // WhereOrPrefixLT builds `prefix.column < value` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixLT. -func (m *Model) WhereOrPrefixLT(prefix string, column string, value interface{}) *Model { +func (m *Model) WhereOrPrefixLT(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixLT(prefix, column, value)) } // WhereOrPrefixLTE builds `prefix.column <= value` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixLTE. -func (m *Model) WhereOrPrefixLTE(prefix string, column string, value interface{}) *Model { +func (m *Model) WhereOrPrefixLTE(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixLTE(prefix, column, value)) } // WhereOrPrefixGT builds `prefix.column > value` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixGT. -func (m *Model) WhereOrPrefixGT(prefix string, column string, value interface{}) *Model { +func (m *Model) WhereOrPrefixGT(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixGT(prefix, column, value)) } // WhereOrPrefixGTE builds `prefix.column >= value` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixGTE. -func (m *Model) WhereOrPrefixGTE(prefix string, column string, value interface{}) *Model { +func (m *Model) WhereOrPrefixGTE(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixGTE(prefix, column, value)) } // WhereOrPrefixBetween builds `prefix.column BETWEEN min AND max` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixBetween. -func (m *Model) WhereOrPrefixBetween(prefix string, column string, min, max interface{}) *Model { +func (m *Model) WhereOrPrefixBetween(prefix string, column string, min, max any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixBetween(prefix, column, min, max)) } // WhereOrPrefixLike builds `prefix.column LIKE like` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixLike. -func (m *Model) WhereOrPrefixLike(prefix string, column string, like interface{}) *Model { +func (m *Model) WhereOrPrefixLike(prefix string, column string, like any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixLike(prefix, column, like)) } // WhereOrPrefixIn builds `prefix.column IN (in)` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixIn. -func (m *Model) WhereOrPrefixIn(prefix string, column string, in interface{}) *Model { +func (m *Model) WhereOrPrefixIn(prefix string, column string, in any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixIn(prefix, column, in)) } @@ -62,19 +62,19 @@ func (m *Model) WhereOrPrefixNull(prefix string, columns ...string) *Model { // WhereOrPrefixNotBetween builds `prefix.column NOT BETWEEN min AND max` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixNotBetween. -func (m *Model) WhereOrPrefixNotBetween(prefix string, column string, min, max interface{}) *Model { +func (m *Model) WhereOrPrefixNotBetween(prefix string, column string, min, max any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixNotBetween(prefix, column, min, max)) } // WhereOrPrefixNotLike builds `prefix.column NOT LIKE like` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixNotLike. -func (m *Model) WhereOrPrefixNotLike(prefix string, column string, like interface{}) *Model { +func (m *Model) WhereOrPrefixNotLike(prefix string, column string, like any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixNotLike(prefix, column, like)) } // WhereOrPrefixNotIn builds `prefix.column NOT IN (in)` statement. // See WhereBuilder.WhereOrPrefixNotIn. -func (m *Model) WhereOrPrefixNotIn(prefix string, column string, in interface{}) *Model { +func (m *Model) WhereOrPrefixNotIn(prefix string, column string, in any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixNotIn(prefix, column, in)) } @@ -86,6 +86,6 @@ func (m *Model) WhereOrPrefixNotNull(prefix string, columns ...string) *Model { // WhereOrPrefixNot builds `prefix.column != value` statement in `OR` conditions. // See WhereBuilder.WhereOrPrefixNot. -func (m *Model) WhereOrPrefixNot(prefix string, column string, value interface{}) *Model { +func (m *Model) WhereOrPrefixNot(prefix string, column string, value any) *Model { return m.callWhereBuilder(m.whereBuilder.WhereOrPrefixNot(prefix, column, value)) } diff --git a/database/gdb/gdb_model_with.go b/database/gdb/gdb_model_with.go index 31e38b2f780..eaea5300b4d 100644 --- a/database/gdb/gdb_model_with.go +++ b/database/gdb/gdb_model_with.go @@ -43,7 +43,7 @@ import ( // Or: // // db.With(UserDetail{}, UserScores{}).Scan(xxx) -func (m *Model) With(objects ...interface{}) *Model { +func (m *Model) With(objects ...any) *Model { model := m.getModel() for _, object := range objects { if m.tables == "" { @@ -66,7 +66,7 @@ func (m *Model) WithAll() *Model { } // doWithScanStruct handles model association operations feature for single struct. -func (m *Model) doWithScanStruct(pointer interface{}) error { +func (m *Model) doWithScanStruct(pointer any) error { if len(m.withArray) == 0 && !m.withAll { return nil } @@ -124,7 +124,7 @@ func (m *Model) doWithScanStruct(pointer interface{}) error { fieldKeys []string relatedSourceName = array[0] relatedTargetName = array[1] - relatedTargetValue interface{} + relatedTargetValue any ) // Find the value of related attribute from `pointer`. for attributeName, attributeValue := range currentStructFieldMap { @@ -141,7 +141,7 @@ func (m *Model) doWithScanStruct(pointer interface{}) error { ) } bindToReflectValue := field.Value - if bindToReflectValue.Kind() != reflect.Ptr && bindToReflectValue.CanAddr() { + if bindToReflectValue.Kind() != reflect.Pointer && bindToReflectValue.CanAddr() { bindToReflectValue = bindToReflectValue.Addr() } @@ -189,7 +189,7 @@ func (m *Model) doWithScanStruct(pointer interface{}) error { // doWithScanStructs handles model association operations feature for struct slice. // Also see doWithScanStruct. -func (m *Model) doWithScanStructs(pointer interface{}) error { +func (m *Model) doWithScanStructs(pointer any) error { if len(m.withArray) == 0 && !m.withAll { return nil } @@ -251,7 +251,7 @@ func (m *Model) doWithScanStructs(pointer interface{}) error { fieldKeys []string relatedSourceName = array[0] relatedTargetName = array[1] - relatedTargetValue interface{} + relatedTargetValue any ) // Find the value slice of related attribute from `pointer`. for attributeName := range currentStructFieldMap { diff --git a/database/gdb/gdb_statement.go b/database/gdb/gdb_statement.go index 4ba93581cc6..d5d38075c45 100644 --- a/database/gdb/gdb_statement.go +++ b/database/gdb/gdb_statement.go @@ -29,7 +29,7 @@ type Stmt struct { // ExecContext executes a prepared statement with the given arguments and // returns a Result summarizing the effect of the statement. -func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error) { +func (s *Stmt) ExecContext(ctx context.Context, args ...any) (sql.Result, error) { out, err := s.core.db.DoCommit(ctx, DoCommitInput{ Stmt: s.Stmt, Link: s.link, @@ -43,7 +43,7 @@ func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (sql.Result // QueryContext executes a prepared query statement with the given arguments // and returns the query results as a *Rows. -func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*sql.Rows, error) { +func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*sql.Rows, error) { out, err := s.core.db.DoCommit(ctx, DoCommitInput{ Stmt: s.Stmt, Link: s.link, @@ -67,7 +67,7 @@ func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*sql.Rows // If the query selects no rows, the *Row's Scan will return ErrNoRows. // Otherwise, the *Row's Scan scans the first selected row and discards // the rest. -func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *sql.Row { +func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *sql.Row { out, err := s.core.db.DoCommit(ctx, DoCommitInput{ Stmt: s.Stmt, Link: s.link, @@ -87,13 +87,13 @@ func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *sql.Ro // Exec executes a prepared statement with the given arguments and // returns a Result summarizing the effect of the statement. -func (s *Stmt) Exec(args ...interface{}) (sql.Result, error) { +func (s *Stmt) Exec(args ...any) (sql.Result, error) { return s.ExecContext(context.Background(), args...) } // Query executes a prepared query statement with the given arguments // and returns the query results as a *Rows. -func (s *Stmt) Query(args ...interface{}) (*sql.Rows, error) { +func (s *Stmt) Query(args ...any) (*sql.Rows, error) { return s.QueryContext(context.Background(), args...) } @@ -108,7 +108,7 @@ func (s *Stmt) Query(args ...interface{}) (*sql.Rows, error) { // // var name string // err := nameByUseridStmt.QueryRow(id).Scan(&name) -func (s *Stmt) QueryRow(args ...interface{}) *sql.Row { +func (s *Stmt) QueryRow(args ...any) *sql.Row { return s.QueryRowContext(context.Background(), args...) } diff --git a/database/gdb/gdb_type_record.go b/database/gdb/gdb_type_record.go index 93470551026..b0063fb1b8d 100644 --- a/database/gdb/gdb_type_record.go +++ b/database/gdb/gdb_type_record.go @@ -27,9 +27,9 @@ func (r Record) Xml(rootTag ...string) string { return content } -// Map converts `r` to map[string]interface{}. +// Map converts `r` to map[string]any. func (r Record) Map() Map { - m := make(map[string]interface{}) + m := make(map[string]any) for k, v := range r { m[k] = v.Val() } @@ -45,7 +45,7 @@ func (r Record) GMap() *gmap.StrAnyMap { // Note that the parameter `pointer` should be type of *struct/**struct. // // Note that it returns sql.ErrNoRows if `r` is empty. -func (r Record) Struct(pointer interface{}) error { +func (r Record) Struct(pointer any) error { // If the record is empty, it returns error. if r.IsEmpty() { if !empty.IsNil(pointer, true) { diff --git a/database/gdb/gdb_type_result.go b/database/gdb/gdb_type_result.go index e1bff6184cc..d35f7b0d86d 100644 --- a/database/gdb/gdb_type_result.go +++ b/database/gdb/gdb_type_result.go @@ -102,7 +102,7 @@ func (r Result) MapKeyValue(key string) map[string]Value { var ( s string m = make(map[string]Value) - tempMap = make(map[string][]interface{}) + tempMap = make(map[string][]any) hasMultiValues bool ) for _, item := range r { @@ -192,7 +192,7 @@ func (r Result) RecordKeyUint(key string) map[uint]Record { // Structs converts `r` to struct slice. // Note that the parameter `pointer` should be type of *[]struct/*[]*struct. -func (r Result) Structs(pointer interface{}) (err error) { +func (r Result) Structs(pointer any) (err error) { // If the result is empty and the target pointer is not empty, it returns error. if r.IsEmpty() { if !empty.IsEmpty(pointer, true) { diff --git a/database/gdb/gdb_type_result_scanlist.go b/database/gdb/gdb_type_result_scanlist.go index d2d32284686..bea9aa76b7c 100644 --- a/database/gdb/gdb_type_result_scanlist.go +++ b/database/gdb/gdb_type_result_scanlist.go @@ -91,7 +91,7 @@ import ( // given `relation` parameter. // // 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) { +func (r Result) ScanList(structSlicePointer any, bindToAttrName string, relationAttrNameAndFields ...string) (err error) { out, err := checkGetSliceElementInfoForScanList(structSlicePointer, bindToAttrName) if err != nil { return err @@ -124,7 +124,7 @@ type checkGetSliceElementInfoForScanListOutput struct { BindToAttrType reflect.Type } -func checkGetSliceElementInfoForScanList(structSlicePointer interface{}, bindToAttrName string) (out *checkGetSliceElementInfoForScanListOutput, err error) { +func checkGetSliceElementInfoForScanList(structSlicePointer any, bindToAttrName string) (out *checkGetSliceElementInfoForScanListOutput, err error) { // Necessary checks for parameters. if structSlicePointer == nil { return nil, gerror.NewCode(gcode.CodeInvalidParameter, `structSlicePointer cannot be nil`) @@ -141,7 +141,7 @@ func checkGetSliceElementInfoForScanList(structSlicePointer interface{}, bindToA reflectValue = reflectValue.Elem() reflectKind = reflectValue.Kind() } - if reflectKind != reflect.Ptr { + if reflectKind != reflect.Pointer { return nil, gerror.NewCodef( gcode.CodeInvalidParameter, "structSlicePointer should be type of *[]struct/*[]*struct, but got: %s", @@ -154,7 +154,7 @@ func checkGetSliceElementInfoForScanList(structSlicePointer interface{}, bindToA // Find the element struct type of the slice. reflectType = reflectValue.Type().Elem().Elem() reflectKind = reflectType.Kind() - for reflectKind == reflect.Ptr { + for reflectKind == reflect.Pointer { reflectType = reflectType.Elem() reflectKind = reflectType.Kind() } @@ -179,7 +179,7 @@ func checkGetSliceElementInfoForScanList(structSlicePointer interface{}, bindToA // Find the attribute struct type for ORM fields filtering. reflectType = structField.Type reflectKind = reflectType.Kind() - for reflectKind == reflect.Ptr { + for reflectKind == reflect.Pointer { reflectType = reflectType.Elem() reflectKind = reflectType.Kind() } @@ -194,7 +194,7 @@ func checkGetSliceElementInfoForScanList(structSlicePointer interface{}, bindToA type doScanListInput struct { Model *Model Result Result - StructSlicePointer interface{} + StructSlicePointer any StructSliceValue reflect.Value BindToAttrName string RelationAttrName string @@ -219,7 +219,7 @@ func doScanList(in doScanListInput) (err error) { 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 := in.StructSliceValue.Index(0); v.Kind() != reflect.Ptr { + if v := in.StructSliceValue.Index(0); v.Kind() != reflect.Pointer { return sql.ErrNoRows } } @@ -301,7 +301,7 @@ func doScanList(in doScanListInput) (err error) { bindToAttrType reflect.Type bindToAttrField reflect.StructField ) - if arrayItemType.Kind() == reflect.Ptr { + if arrayItemType.Kind() == reflect.Pointer { if bindToAttrField, ok = arrayItemType.Elem().FieldByName(in.BindToAttrName); !ok { return gerror.NewCodef( gcode.CodeInvalidParameter, @@ -330,7 +330,7 @@ func doScanList(in doScanListInput) (err error) { for i := 0; i < arrayValue.Len(); i++ { arrayElemValue := arrayValue.Index(i) // The FieldByName should be called on non-pointer reflect.Value. - if arrayElemValue.Kind() == reflect.Ptr { + if arrayElemValue.Kind() == reflect.Pointer { // Like: []*Entity arrayElemValue = arrayElemValue.Elem() if !arrayElemValue.IsValid() { @@ -349,7 +349,7 @@ func doScanList(in doScanListInput) (err error) { if in.RelationAttrName != "" { // Attribute value of current slice element. relationFromAttrValue = arrayElemValue.FieldByName(in.RelationAttrName) - if relationFromAttrValue.Kind() == reflect.Ptr { + if relationFromAttrValue.Kind() == reflect.Pointer { relationFromAttrValue = relationFromAttrValue.Elem() } } else { @@ -410,7 +410,7 @@ func doScanList(in doScanListInput) (err error) { ) } - case reflect.Ptr: + case reflect.Pointer: var element reflect.Value if bindToAttrValue.IsNil() { element = reflect.New(bindToAttrType.Elem()).Elem() diff --git a/database/gredis/gredis_adapter.go b/database/gredis/gredis_adapter.go index c941ab0f816..321ee96c0f9 100644 --- a/database/gredis/gredis_adapter.go +++ b/database/gredis/gredis_adapter.go @@ -35,7 +35,7 @@ type AdapterGroup interface { type AdapterOperation interface { // Do send a command to the server and returns the received reply. // It uses json.Marshal for struct/slice/map type values before committing them to redis. - Do(ctx context.Context, command string, args ...interface{}) (*gvar.Var, error) + Do(ctx context.Context, command string, args ...any) (*gvar.Var, error) // Conn retrieves and returns a connection object for continuous operations. // Note that you should call Close function manually if you do not use this connection any further. @@ -51,7 +51,7 @@ type Conn interface { // Do send a command to the server and returns the received reply. // It uses json.Marshal for struct/slice/map type values before committing them to redis. - Do(ctx context.Context, command string, args ...interface{}) (result *gvar.Var, err error) + Do(ctx context.Context, command string, args ...any) (result *gvar.Var, err error) // Close puts the connection back to connection pool. Close(ctx context.Context) (err error) diff --git a/database/gredis/gredis_config.go b/database/gredis/gredis_config.go index ca6d34e1840..69d410a8f3f 100644 --- a/database/gredis/gredis_config.go +++ b/database/gredis/gredis_config.go @@ -68,7 +68,7 @@ func SetConfig(config *Config, name ...string) { // SetConfigByMap sets the global configuration for specified group with map. // If `name` is not passed, it sets configuration for the default group name. -func SetConfigByMap(m map[string]interface{}, name ...string) error { +func SetConfigByMap(m map[string]any, name ...string) error { group := DefaultGroupName if len(name) > 0 { group = name[0] @@ -82,7 +82,7 @@ func SetConfigByMap(m map[string]interface{}, name ...string) error { } // ConfigFromMap parses and returns config from given map. -func ConfigFromMap(m map[string]interface{}) (config *Config, err error) { +func ConfigFromMap(m map[string]any) (config *Config, err error) { config = &Config{} if err = gconv.Scan(m, config); err != nil { err = gerror.NewCodef(gcode.CodeInvalidConfiguration, `invalid redis configuration: %#v`, m) diff --git a/database/gredis/gredis_instance.go b/database/gredis/gredis_instance.go index 2805d557af6..68a2f67e240 100644 --- a/database/gredis/gredis_instance.go +++ b/database/gredis/gredis_instance.go @@ -26,7 +26,7 @@ func Instance(name ...string) *Redis { if len(name) > 0 && name[0] != "" { group = name[0] } - v := localInstances.GetOrSetFuncLock(group, func() interface{} { + v := localInstances.GetOrSetFuncLock(group, func() any { if config, ok := GetConfig(group); ok { r, err := New(config) if err != nil { diff --git a/database/gredis/gredis_redis.go b/database/gredis/gredis_redis.go index 5b24be32daa..3c797771585 100644 --- a/database/gredis/gredis_redis.go +++ b/database/gredis/gredis_redis.go @@ -94,7 +94,7 @@ func (r *Redis) Conn(ctx context.Context) (Conn, error) { // Do send a command to the server and returns the received reply. // It uses json.Marshal for struct/slice/map type values before committing them to redis. -func (r *Redis) Do(ctx context.Context, command string, args ...interface{}) (*gvar.Var, error) { +func (r *Redis) Do(ctx context.Context, command string, args ...any) (*gvar.Var, error) { if r == nil { return nil, gerror.NewCode(gcode.CodeInvalidParameter, errorNilRedis) } @@ -114,7 +114,7 @@ func (r *Redis) MustConn(ctx context.Context) Conn { } // MustDo performs as function Do, but it panics if any error occurs internally. -func (r *Redis) MustDo(ctx context.Context, command string, args ...interface{}) *gvar.Var { +func (r *Redis) MustDo(ctx context.Context, command string, args ...any) *gvar.Var { v, err := r.Do(ctx, command, args...) if err != nil { panic(err) diff --git a/database/gredis/gredis_redis_group_hash.go b/database/gredis/gredis_redis_group_hash.go index ab398447241..8d4c3e743d5 100644 --- a/database/gredis/gredis_redis_group_hash.go +++ b/database/gredis/gredis_redis_group_hash.go @@ -15,8 +15,8 @@ import ( // IGroupHash manages redis hash operations. // Implements see redis.GroupHash. type IGroupHash interface { - HSet(ctx context.Context, key string, fields map[string]interface{}) (int64, error) - HSetNX(ctx context.Context, key, field string, value interface{}) (int64, error) + HSet(ctx context.Context, key string, fields map[string]any) (int64, error) + HSetNX(ctx context.Context, key, field string, value any) (int64, error) HGet(ctx context.Context, key, field string) (*gvar.Var, error) HStrLen(ctx context.Context, key, field string) (int64, error) HExists(ctx context.Context, key, field string) (int64, error) @@ -24,7 +24,7 @@ type IGroupHash interface { HLen(ctx context.Context, key string) (int64, error) HIncrBy(ctx context.Context, key, field string, increment int64) (int64, error) HIncrByFloat(ctx context.Context, key, field string, increment float64) (float64, error) - HMSet(ctx context.Context, key string, fields map[string]interface{}) error + HMSet(ctx context.Context, key string, fields map[string]any) error HMGet(ctx context.Context, key string, fields ...string) (gvar.Vars, error) HKeys(ctx context.Context, key string) ([]string, error) HVals(ctx context.Context, key string) (gvar.Vars, error) diff --git a/database/gredis/gredis_redis_group_list.go b/database/gredis/gredis_redis_group_list.go index fa989170c7b..b13131f6126 100644 --- a/database/gredis/gredis_redis_group_list.go +++ b/database/gredis/gredis_redis_group_list.go @@ -15,17 +15,17 @@ import ( // IGroupList manages redis list operations. // Implements see redis.GroupList. type IGroupList interface { - LPush(ctx context.Context, key string, values ...interface{}) (int64, error) - LPushX(ctx context.Context, key string, element interface{}, elements ...interface{}) (int64, error) - RPush(ctx context.Context, key string, values ...interface{}) (int64, error) - RPushX(ctx context.Context, key string, value interface{}) (int64, error) + LPush(ctx context.Context, key string, values ...any) (int64, error) + LPushX(ctx context.Context, key string, element any, elements ...any) (int64, error) + RPush(ctx context.Context, key string, values ...any) (int64, error) + RPushX(ctx context.Context, key string, value any) (int64, error) LPop(ctx context.Context, key string, count ...int) (*gvar.Var, error) RPop(ctx context.Context, key string, count ...int) (*gvar.Var, error) - LRem(ctx context.Context, key string, count int64, value interface{}) (int64, error) + LRem(ctx context.Context, key string, count int64, value any) (int64, error) LLen(ctx context.Context, key string) (int64, error) LIndex(ctx context.Context, key string, index int64) (*gvar.Var, error) - LInsert(ctx context.Context, key string, op LInsertOp, pivot, value interface{}) (int64, error) - LSet(ctx context.Context, key string, index int64, value interface{}) (*gvar.Var, error) + LInsert(ctx context.Context, key string, op LInsertOp, pivot, value any) (int64, error) + LSet(ctx context.Context, key string, index int64, value any) (*gvar.Var, error) LRange(ctx context.Context, key string, start, stop int64) (gvar.Vars, error) LTrim(ctx context.Context, key string, start, stop int64) error BLPop(ctx context.Context, timeout int64, keys ...string) (gvar.Vars, error) diff --git a/database/gredis/gredis_redis_group_pubsub.go b/database/gredis/gredis_redis_group_pubsub.go index 2e4bd5538e3..c0d435ffc21 100644 --- a/database/gredis/gredis_redis_group_pubsub.go +++ b/database/gredis/gredis_redis_group_pubsub.go @@ -14,7 +14,7 @@ import ( // IGroupPubSub manages redis pub/sub operations. // Implements see redis.GroupPubSub. type IGroupPubSub interface { - Publish(ctx context.Context, channel string, message interface{}) (int64, error) + Publish(ctx context.Context, channel string, message any) (int64, error) Subscribe(ctx context.Context, channel string, channels ...string) (Conn, []*Subscription, error) PSubscribe(ctx context.Context, pattern string, patterns ...string) (Conn, []*Subscription, error) } diff --git a/database/gredis/gredis_redis_group_script.go b/database/gredis/gredis_redis_group_script.go index e2ef1fc4e3f..d7a8006ab53 100644 --- a/database/gredis/gredis_redis_group_script.go +++ b/database/gredis/gredis_redis_group_script.go @@ -15,8 +15,8 @@ import ( // IGroupScript manages redis script operations. // Implements see redis.GroupScript. type IGroupScript interface { - Eval(ctx context.Context, script string, numKeys int64, keys []string, args []interface{}) (*gvar.Var, error) - EvalSha(ctx context.Context, sha1 string, numKeys int64, keys []string, args []interface{}) (*gvar.Var, error) + Eval(ctx context.Context, script string, numKeys int64, keys []string, args []any) (*gvar.Var, error) + EvalSha(ctx context.Context, sha1 string, numKeys int64, keys []string, args []any) (*gvar.Var, error) ScriptLoad(ctx context.Context, script string) (string, error) ScriptExists(ctx context.Context, sha1 string, sha1s ...string) (map[string]bool, error) ScriptFlush(ctx context.Context, option ...ScriptFlushOption) error diff --git a/database/gredis/gredis_redis_group_set.go b/database/gredis/gredis_redis_group_set.go index 27e04fbfeb0..d84b4f22ef3 100644 --- a/database/gredis/gredis_redis_group_set.go +++ b/database/gredis/gredis_redis_group_set.go @@ -15,15 +15,15 @@ import ( // IGroupSet manages redis set operations. // Implements see redis.GroupSet. type IGroupSet interface { - SAdd(ctx context.Context, key string, member interface{}, members ...interface{}) (int64, error) - SIsMember(ctx context.Context, key string, member interface{}) (int64, error) + SAdd(ctx context.Context, key string, member any, members ...any) (int64, error) + SIsMember(ctx context.Context, key string, member any) (int64, error) SPop(ctx context.Context, key string, count ...int) (*gvar.Var, error) SRandMember(ctx context.Context, key string, count ...int) (*gvar.Var, error) - SRem(ctx context.Context, key string, member interface{}, members ...interface{}) (int64, error) - SMove(ctx context.Context, source, destination string, member interface{}) (int64, error) + SRem(ctx context.Context, key string, member any, members ...any) (int64, error) + SMove(ctx context.Context, source, destination string, member any) (int64, error) SCard(ctx context.Context, key string) (int64, error) SMembers(ctx context.Context, key string) (gvar.Vars, error) - SMIsMember(ctx context.Context, key, member interface{}, members ...interface{}) ([]int, error) + SMIsMember(ctx context.Context, key, member any, members ...any) ([]int, error) SInter(ctx context.Context, key string, keys ...string) (gvar.Vars, error) SInterStore(ctx context.Context, destination string, key string, keys ...string) (int64, error) SUnion(ctx context.Context, key string, keys ...string) (gvar.Vars, error) diff --git a/database/gredis/gredis_redis_group_sorted_set.go b/database/gredis/gredis_redis_group_sorted_set.go index 83367136c74..c465b55d724 100644 --- a/database/gredis/gredis_redis_group_sorted_set.go +++ b/database/gredis/gredis_redis_group_sorted_set.go @@ -16,15 +16,15 @@ import ( // Implements see redis.GroupSortedSet. type IGroupSortedSet interface { ZAdd(ctx context.Context, key string, option *ZAddOption, member ZAddMember, members ...ZAddMember) (*gvar.Var, error) - ZScore(ctx context.Context, key string, member interface{}) (float64, error) - ZIncrBy(ctx context.Context, key string, increment float64, member interface{}) (float64, error) + ZScore(ctx context.Context, key string, member any) (float64, error) + ZIncrBy(ctx context.Context, key string, increment float64, member any) (float64, error) ZCard(ctx context.Context, key string) (int64, error) ZCount(ctx context.Context, key string, min, max string) (int64, error) ZRange(ctx context.Context, key string, start, stop int64, option ...ZRangeOption) (gvar.Vars, error) ZRevRange(ctx context.Context, key string, start, stop int64, option ...ZRevRangeOption) (*gvar.Var, error) - ZRank(ctx context.Context, key string, member interface{}) (int64, error) - ZRevRank(ctx context.Context, key string, member interface{}) (int64, error) - ZRem(ctx context.Context, key string, member interface{}, members ...interface{}) (int64, error) + ZRank(ctx context.Context, key string, member any) (int64, error) + ZRevRank(ctx context.Context, key string, member any) (int64, error) + ZRem(ctx context.Context, key string, member any, members ...any) (int64, error) ZRemRangeByRank(ctx context.Context, key string, start, stop int64) (int64, error) ZRemRangeByScore(ctx context.Context, key string, min, max string) (int64, error) ZRemRangeByLex(ctx context.Context, key string, min, max string) (int64, error) @@ -56,7 +56,7 @@ type ZAddOption struct { // ZAddMember is element struct for set. type ZAddMember struct { Score float64 - Member interface{} + Member any } // ZRangeOption provides extra option for ZRange function. diff --git a/database/gredis/gredis_redis_group_string.go b/database/gredis/gredis_redis_group_string.go index 88e82704dbb..acef8742a52 100644 --- a/database/gredis/gredis_redis_group_string.go +++ b/database/gredis/gredis_redis_group_string.go @@ -15,13 +15,13 @@ import ( // IGroupString manages redis string operations. // Implements see redis.GroupString. type IGroupString interface { - Set(ctx context.Context, key string, value interface{}, option ...SetOption) (*gvar.Var, error) - SetNX(ctx context.Context, key string, value interface{}) (bool, error) - SetEX(ctx context.Context, key string, value interface{}, ttlInSeconds int64) error + Set(ctx context.Context, key string, value any, option ...SetOption) (*gvar.Var, error) + SetNX(ctx context.Context, key string, value any) (bool, error) + SetEX(ctx context.Context, key string, value any, ttlInSeconds int64) error Get(ctx context.Context, key string) (*gvar.Var, error) GetDel(ctx context.Context, key string) (*gvar.Var, error) GetEX(ctx context.Context, key string, option ...GetEXOption) (*gvar.Var, error) - GetSet(ctx context.Context, key string, value interface{}) (*gvar.Var, error) + GetSet(ctx context.Context, key string, value any) (*gvar.Var, error) StrLen(ctx context.Context, key string) (int64, error) Append(ctx context.Context, key string, value string) (int64, error) SetRange(ctx context.Context, key string, offset int64, value string) (int64, error) @@ -31,8 +31,8 @@ type IGroupString interface { IncrByFloat(ctx context.Context, key string, increment float64) (float64, error) Decr(ctx context.Context, key string) (int64, error) DecrBy(ctx context.Context, key string, decrement int64) (int64, error) - MSet(ctx context.Context, keyValueMap map[string]interface{}) error - MSetNX(ctx context.Context, keyValueMap map[string]interface{}) (bool, error) + MSet(ctx context.Context, keyValueMap map[string]any) error + MSetNX(ctx context.Context, keyValueMap map[string]any) (bool, error) MGet(ctx context.Context, keys ...string) (map[string]*gvar.Var, error) } diff --git a/debug/gdebug/gdebug_caller.go b/debug/gdebug/gdebug_caller.go index e5863e25f0c..dcad18a8a4c 100644 --- a/debug/gdebug/gdebug_caller.go +++ b/debug/gdebug/gdebug_caller.go @@ -187,12 +187,12 @@ func CallerFileLineShort() string { } // FuncPath returns the complete function path of given `f`. -func FuncPath(f interface{}) string { +func FuncPath(f any) string { return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() } // FuncName returns the function name of given `f`. -func FuncName(f interface{}) string { +func FuncName(f any) string { path := FuncPath(f) if path == "" { return "" diff --git a/encoding/gbinary/gbinary.go b/encoding/gbinary/gbinary.go index 5fbc48477f8..575c6089919 100644 --- a/encoding/gbinary/gbinary.go +++ b/encoding/gbinary/gbinary.go @@ -9,15 +9,15 @@ // Note that package gbinary encodes the data using LittleEndian in default. package gbinary -func Encode(values ...interface{}) []byte { +func Encode(values ...any) []byte { return LeEncode(values...) } -func EncodeByLength(length int, values ...interface{}) []byte { +func EncodeByLength(length int, values ...any) []byte { return LeEncodeByLength(length, values...) } -func Decode(b []byte, values ...interface{}) error { +func Decode(b []byte, values ...any) error { return LeDecode(b, values...) } diff --git a/encoding/gbinary/gbinary_be.go b/encoding/gbinary/gbinary_be.go index 6f608548930..2c4718c7a74 100644 --- a/encoding/gbinary/gbinary_be.go +++ b/encoding/gbinary/gbinary_be.go @@ -23,7 +23,7 @@ import ( // // It supports common variable type asserting, and finally it uses fmt.Sprintf converting // value to string and then to bytes. -func BeEncode(values ...interface{}) []byte { +func BeEncode(values ...any) []byte { buf := new(bytes.Buffer) for i := 0; i < len(values); i++ { if values[i] == nil { @@ -71,7 +71,7 @@ func BeEncode(values ...interface{}) []byte { return buf.Bytes() } -func BeEncodeByLength(length int, values ...interface{}) []byte { +func BeEncodeByLength(length int, values ...any) []byte { b := BeEncode(values...) if len(b) < length { b = append(b, make([]byte, length-len(b))...) @@ -81,7 +81,7 @@ func BeEncodeByLength(length int, values ...interface{}) []byte { return b } -func BeDecode(b []byte, values ...interface{}) error { +func BeDecode(b []byte, values ...any) error { var ( err error buf = bytes.NewBuffer(b) diff --git a/encoding/gbinary/gbinary_le.go b/encoding/gbinary/gbinary_le.go index b648c09d260..afaf629fed1 100644 --- a/encoding/gbinary/gbinary_le.go +++ b/encoding/gbinary/gbinary_le.go @@ -23,7 +23,7 @@ import ( // // It supports common variable type asserting, and finally it uses fmt.Sprintf converting // value to string and then to bytes. -func LeEncode(values ...interface{}) []byte { +func LeEncode(values ...any) []byte { buf := new(bytes.Buffer) for i := 0; i < len(values); i++ { if values[i] == nil { @@ -71,7 +71,7 @@ func LeEncode(values ...interface{}) []byte { return buf.Bytes() } -func LeEncodeByLength(length int, values ...interface{}) []byte { +func LeEncodeByLength(length int, values ...any) []byte { b := LeEncode(values...) if len(b) < length { b = append(b, make([]byte, length-len(b))...) @@ -81,7 +81,7 @@ func LeEncodeByLength(length int, values ...interface{}) []byte { return b } -func LeDecode(b []byte, values ...interface{}) error { +func LeDecode(b []byte, values ...any) error { var ( err error buf = bytes.NewBuffer(b) diff --git a/encoding/gbinary/gbinary_z_unit_test.go b/encoding/gbinary/gbinary_z_unit_test.go index 060f38cc3ff..21ee2086617 100644 --- a/encoding/gbinary/gbinary_z_unit_test.go +++ b/encoding/gbinary/gbinary_z_unit_test.go @@ -20,7 +20,7 @@ type User struct { Url string } -var testData = map[string]interface{}{ +var testData = map[string]any{ //"nil": nil, "int": int(123), "int8": int8(-99), diff --git a/encoding/ghtml/ghtml.go b/encoding/ghtml/ghtml.go index d027fb192de..97c3decb2b4 100644 --- a/encoding/ghtml/ghtml.go +++ b/encoding/ghtml/ghtml.go @@ -72,13 +72,13 @@ func SpecialCharsDecode(s string) string { // OK: SpecialCharsMapOrStruct(m) // OK: SpecialCharsMapOrStruct(&s) // Error: SpecialCharsMapOrStruct(s) -func SpecialCharsMapOrStruct(mapOrStruct interface{}) error { +func SpecialCharsMapOrStruct(mapOrStruct any) error { var ( reflectValue = reflect.ValueOf(mapOrStruct) reflectKind = reflectValue.Kind() originalKind = reflectKind ) - for reflectValue.IsValid() && (reflectKind == reflect.Ptr || reflectKind == reflect.Interface) { + for reflectValue.IsValid() && (reflectKind == reflect.Pointer || reflectKind == reflect.Interface) { reflectValue = reflectValue.Elem() reflectKind = reflectValue.Kind() } @@ -106,7 +106,7 @@ func SpecialCharsMapOrStruct(mapOrStruct interface{}) error { } case reflect.Struct: - if originalKind != reflect.Ptr { + if originalKind != reflect.Pointer { return gerror.NewCodef( gcode.CodeInvalidParameter, `invalid input parameter type "%s", should be type of pointer to struct`, diff --git a/encoding/gini/gini.go b/encoding/gini/gini.go index a9f0e821d90..90e88015898 100644 --- a/encoding/gini/gini.go +++ b/encoding/gini/gini.go @@ -20,10 +20,10 @@ import ( ) // Decode converts INI format to map. -func Decode(data []byte) (res map[string]interface{}, err error) { - res = make(map[string]interface{}) +func Decode(data []byte) (res map[string]any, err error) { + res = make(map[string]any) var ( - fieldMap = make(map[string]interface{}) + fieldMap = make(map[string]any) bytesReader = bytes.NewReader(data) bufioReader = bufio.NewReader(bytesReader) section string @@ -58,7 +58,7 @@ func Decode(data []byte) (res map[string]interface{}, err error) { lastSection = section } else if lastSection != section { lastSection = section - fieldMap = make(map[string]interface{}) + fieldMap = make(map[string]any) } haveSection = true } else if !haveSection { @@ -79,16 +79,16 @@ func Decode(data []byte) (res map[string]interface{}, err error) { } // Encode converts map to INI format. -func Encode(data map[string]interface{}) (res []byte, err error) { +func Encode(data map[string]any) (res []byte, err error) { var ( n int w = new(bytes.Buffer) - m map[string]interface{} + m map[string]any ok bool ) for section, item := range data { // Section key-value pairs. - if m, ok = item.(map[string]interface{}); ok { + if m, ok = item.(map[string]any); ok { n, err = w.WriteString(fmt.Sprintf("[%s]\n", section)) if err != nil || n == 0 { return nil, gerror.Wrapf(err, "w.WriteString failed") diff --git a/encoding/gini/gini_z_unit_test.go b/encoding/gini/gini_z_unit_test.go index e3001f7f34f..929572c03ac 100644 --- a/encoding/gini/gini_z_unit_test.go +++ b/encoding/gini/gini_z_unit_test.go @@ -40,12 +40,12 @@ func TestDecode(t *testing.T) { if err != nil { gtest.Fatal(err) } - t.Assert(res["addr"].(map[string]interface{})["ip"], "127.0.0.1") - t.Assert(res["addr"].(map[string]interface{})["port"], "9001") - t.Assert(res["addr"].(map[string]interface{})["command"], `/bin/echo "gf=GoFrame"`) - t.Assert(res["DBINFO"].(map[string]interface{})["user"], "root") - t.Assert(res["DBINFO"].(map[string]interface{})["type"], "mysql") - t.Assert(res["键"].(map[string]interface{})["呵呵"], "值") + t.Assert(res["addr"].(map[string]any)["ip"], "127.0.0.1") + t.Assert(res["addr"].(map[string]any)["port"], "9001") + t.Assert(res["addr"].(map[string]any)["command"], `/bin/echo "gf=GoFrame"`) + t.Assert(res["DBINFO"].(map[string]any)["user"], "root") + t.Assert(res["DBINFO"].(map[string]any)["type"], "mysql") + t.Assert(res["键"].(map[string]any)["呵呵"], "值") }) gtest.C(t, func(t *gtest.T) { @@ -76,10 +76,10 @@ func TestEncode(t *testing.T) { gtest.Fatal(err) } - t.Assert(res["addr"].(map[string]interface{})["ip"], "127.0.0.1") - t.Assert(res["addr"].(map[string]interface{})["port"], "9001") - t.Assert(res["DBINFO"].(map[string]interface{})["user"], "root") - t.Assert(res["DBINFO"].(map[string]interface{})["type"], "mysql") + t.Assert(res["addr"].(map[string]any)["ip"], "127.0.0.1") + t.Assert(res["addr"].(map[string]any)["port"], "9001") + t.Assert(res["DBINFO"].(map[string]any)["user"], "root") + t.Assert(res["DBINFO"].(map[string]any)["type"], "mysql") }) } @@ -99,9 +99,9 @@ func TestToJson(t *testing.T) { iniMap, err := gini.Decode([]byte(iniContent)) t.AssertNil(err) - t.Assert(iniMap["addr"].(map[string]interface{})["ip"], json.Get("addr.ip").String()) - t.Assert(iniMap["addr"].(map[string]interface{})["port"], json.Get("addr.port").String()) - t.Assert(iniMap["DBINFO"].(map[string]interface{})["user"], json.Get("DBINFO.user").String()) - t.Assert(iniMap["DBINFO"].(map[string]interface{})["type"], json.Get("DBINFO.type").String()) + t.Assert(iniMap["addr"].(map[string]any)["ip"], json.Get("addr.ip").String()) + t.Assert(iniMap["addr"].(map[string]any)["port"], json.Get("addr.port").String()) + t.Assert(iniMap["DBINFO"].(map[string]any)["user"], json.Get("DBINFO.user").String()) + t.Assert(iniMap["DBINFO"].(map[string]any)["type"], json.Get("DBINFO.type").String()) }) } diff --git a/encoding/gjson/gjson.go b/encoding/gjson/gjson.go index df11061306c..a939fb6eb84 100644 --- a/encoding/gjson/gjson.go +++ b/encoding/gjson/gjson.go @@ -41,9 +41,9 @@ const ( // Json is the customized JSON struct. type Json struct { mu rwmutex.RWMutex - p *interface{} // Pointer for hierarchical data access, it's the root of data in default. - c byte // Char separator('.' in default). - vc bool // Violence Check(false in default), which is used to access data when the hierarchical data key contains separator char. + p *any // Pointer for hierarchical data access, it's the root of data in default. + c byte // Char separator('.' in default). + vc bool // Violence Check(false in default), which is used to access data when the hierarchical data key contains separator char. } // Options for Json object creating/loading. @@ -51,29 +51,29 @@ type Options struct { Safe bool // Mark this object is for in concurrent-safe usage. This is especially for Json object creating. Tags string // Custom priority tags for decoding, eg: "json,yaml,MyTag". This is especially for struct parsing into Json object. Type ContentType // Type specifies the data content type, eg: json, xml, yaml, toml, ini. - StrNumber bool // StrNumber causes the Decoder to unmarshal a number into an interface{} as a string instead of as a float64. + StrNumber bool // StrNumber causes the Decoder to unmarshal a number into an any as a string instead of as a float64. } // iInterfaces is used for type assert api for Interfaces(). type iInterfaces interface { - Interfaces() []interface{} + Interfaces() []any } // iMapStrAny is the interface support for converting struct parameter to map. type iMapStrAny interface { - MapStrAny() map[string]interface{} + MapStrAny() map[string]any } -// iVal is the interface for underlying interface{} retrieving. +// iVal is the interface for underlying any retrieving. type iVal interface { - Val() interface{} + Val() any } // setValue sets `value` to `j` by `pattern`. // Note: // 1. If value is nil and removed is true, means deleting this value; // 2. It's quite complicated in hierarchical data search, node creating and data assignment; -func (j *Json) setValue(pattern string, value interface{}, removed bool) error { +func (j *Json) setValue(pattern string, value any, removed bool) error { var ( err error array = strings.Split(pattern, string(j.c)) @@ -85,33 +85,33 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { // Initialization checks. if *j.p == nil { if gstr.IsNumeric(array[0]) { - *j.p = make([]interface{}, 0) + *j.p = make([]any, 0) } else { - *j.p = make(map[string]interface{}) + *j.p = make(map[string]any) } } var ( - pparent *interface{} = nil // Parent pointer. - pointer = j.p // Current pointer. + pparent *any = nil // Parent pointer. + pointer = j.p // Current pointer. ) j.mu.Lock() defer j.mu.Unlock() for i := 0; i < length; i++ { switch (*pointer).(type) { - case map[string]interface{}: + case map[string]any: if i == length-1 { if removed && value == nil { // Delete item from map. - delete((*pointer).(map[string]interface{}), array[i]) + delete((*pointer).(map[string]any), array[i]) } else { - if (*pointer).(map[string]interface{}) == nil { - *pointer = map[string]interface{}{} + if (*pointer).(map[string]any) == nil { + *pointer = map[string]any{} } - (*pointer).(map[string]interface{})[array[i]] = value + (*pointer).(map[string]any)[array[i]] = value } } else { // If the key does not exit in the map. - if v, ok := (*pointer).(map[string]interface{})[array[i]]; !ok { + if v, ok := (*pointer).(map[string]any)[array[i]]; !ok { if removed && value == nil { goto done } @@ -119,12 +119,12 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { if gstr.IsNumeric(array[i+1]) { // Creating array node. n, _ := strconv.Atoi(array[i+1]) - var v interface{} = make([]interface{}, n+1) + var v any = make([]any, n+1) pparent = j.setPointerWithValue(pointer, array[i], v) pointer = &v } else { // Creating map node. - var v interface{} = make(map[string]interface{}) + var v any = make(map[string]any) pparent = j.setPointerWithValue(pointer, array[i], v) pointer = &v } @@ -134,13 +134,13 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { } } - case []interface{}: + case []any: // A string key. if !gstr.IsNumeric(array[i]) { if i == length-1 { - *pointer = map[string]interface{}{array[i]: value} + *pointer = map[string]any{array[i]: value} } else { - var v interface{} = make(map[string]interface{}) + var v any = make(map[string]any) *pointer = v pparent = pointer pointer = &v @@ -156,16 +156,16 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { if i == length-1 { // Leaf node. - if len((*pointer).([]interface{})) > valueNum { + if len((*pointer).([]any)) > valueNum { if removed && value == nil { // Deleting element. if pparent == nil { - *pointer = append((*pointer).([]interface{})[:valueNum], (*pointer).([]interface{})[valueNum+1:]...) + *pointer = append((*pointer).([]any)[:valueNum], (*pointer).([]any)[valueNum+1:]...) } else { - j.setPointerWithValue(pparent, array[i-1], append((*pointer).([]interface{})[:valueNum], (*pointer).([]interface{})[valueNum+1:]...)) + j.setPointerWithValue(pparent, array[i-1], append((*pointer).([]any)[:valueNum], (*pointer).([]any)[valueNum+1:]...)) } } else { - (*pointer).([]interface{})[valueNum] = value + (*pointer).([]any)[valueNum] = value } } else { if removed && value == nil { @@ -176,8 +176,8 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { j.setPointerWithValue(pointer, array[i], value) } else { // It is not the root node. - s := make([]interface{}, valueNum+1) - copy(s, (*pointer).([]interface{})) + s := make([]any, valueNum+1) + copy(s, (*pointer).([]any)) s[valueNum] = value j.setPointerWithValue(pparent, array[i-1], s) } @@ -186,10 +186,10 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { // Branch node. if gstr.IsNumeric(array[i+1]) { n, _ := strconv.Atoi(array[i+1]) - pSlice := (*pointer).([]interface{}) + pSlice := (*pointer).([]any) if len(pSlice) > valueNum { item := pSlice[valueNum] - if s, ok := item.([]interface{}); ok { + if s, ok := item.([]any); ok { for i := 0; i < n-len(s); i++ { s = append(s, nil) } @@ -199,7 +199,7 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { if removed && value == nil { goto done } - var v interface{} = make([]interface{}, n+1) + var v any = make([]any, n+1) pparent = j.setPointerWithValue(pointer, array[i], v) pointer = &v } @@ -207,19 +207,19 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { if removed && value == nil { goto done } - var v interface{} = make([]interface{}, n+1) + var v any = make([]any, n+1) pparent = j.setPointerWithValue(pointer, array[i], v) pointer = &v } } else { - pSlice := (*pointer).([]interface{}) + pSlice := (*pointer).([]any) if len(pSlice) > valueNum { pparent = pointer - pointer = &(*pointer).([]interface{})[valueNum] + pointer = &(*pointer).([]any)[valueNum] } else { - s := make([]interface{}, valueNum+1) + s := make([]any, valueNum+1) copy(s, pSlice) - s[valueNum] = make(map[string]interface{}) + s[valueNum] = make(map[string]any) if pparent != nil { // i > 0 j.setPointerWithValue(pparent, array[i-1], s) @@ -227,7 +227,7 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { pointer = &s[valueNum] } else { // i = 0 - var v interface{} = s + var v any = s *pointer = v pparent = pointer pointer = &s[valueNum] @@ -244,7 +244,7 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { } if gstr.IsNumeric(array[i]) { n, _ := strconv.Atoi(array[i]) - s := make([]interface{}, n+1) + s := make([]any, n+1) if i == length-1 { s[n] = value } @@ -255,13 +255,13 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { pparent = pointer } } else { - var v1, v2 interface{} + var v1, v2 any if i == length-1 { - v1 = map[string]interface{}{ + v1 = map[string]any{ array[i]: value, } } else { - v1 = map[string]interface{}{ + v1 = map[string]any{ array[i]: nil, } } @@ -271,7 +271,7 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { *pointer = v1 pparent = pointer } - v2 = v1.(map[string]interface{})[array[i]] + v2 = v1.(map[string]any)[array[i]] pointer = &v2 } } @@ -280,18 +280,18 @@ done: return nil } -// convertValue converts `value` to map[string]interface{} or []interface{}, +// convertValue converts `value` to map[string]any or []any, // which can be supported for hierarchical data access. -func (j *Json) convertValue(value interface{}) (convertedValue interface{}, err error) { +func (j *Json) convertValue(value any) (convertedValue any, err error) { if value == nil { return } switch value.(type) { - case map[string]interface{}: + case map[string]any: return value, nil - case []interface{}: + case []any: return value, nil default: @@ -333,19 +333,19 @@ func (j *Json) convertValue(value interface{}) (convertedValue interface{}, err // setPointerWithValue sets `key`:`value` to `pointer`, the `key` may be a map key or slice index. // It returns the pointer to the new value set. -func (j *Json) setPointerWithValue(pointer *interface{}, key string, value interface{}) *interface{} { +func (j *Json) setPointerWithValue(pointer *any, key string, value any) *any { switch (*pointer).(type) { - case map[string]interface{}: - (*pointer).(map[string]interface{})[key] = value + case map[string]any: + (*pointer).(map[string]any)[key] = value return &value - case []interface{}: + case []any: n, _ := strconv.Atoi(key) - if len((*pointer).([]interface{})) > n { - (*pointer).([]interface{})[n] = value - return &(*pointer).([]interface{})[n] + if len((*pointer).([]any)) > n { + (*pointer).([]any)[n] = value + return &(*pointer).([]any)[n] } else { - s := make([]interface{}, n+1) - copy(s, (*pointer).([]interface{})) + s := make([]any, n+1) + copy(s, (*pointer).([]any)) s[n] = value *pointer = s return &s[n] @@ -357,7 +357,7 @@ func (j *Json) setPointerWithValue(pointer *interface{}, key string, value inter } // getPointerByPattern returns a pointer to the value by specified `pattern`. -func (j *Json) getPointerByPattern(pattern string) *interface{} { +func (j *Json) getPointerByPattern(pattern string) *any { if j.p == nil { return nil } @@ -369,7 +369,7 @@ func (j *Json) getPointerByPattern(pattern string) *interface{} { } // getPointerByPatternWithViolenceCheck returns a pointer to the value of specified `pattern` with violence check. -func (j *Json) getPointerByPatternWithViolenceCheck(pattern string) *interface{} { +func (j *Json) getPointerByPatternWithViolenceCheck(pattern string) *any { if !j.vc { return j.getPointerByPatternWithoutViolenceCheck(pattern) } @@ -419,7 +419,7 @@ func (j *Json) getPointerByPatternWithViolenceCheck(pattern string) *interface{} } // getPointerByPatternWithoutViolenceCheck returns a pointer to the value of specified `pattern`, with no violence check. -func (j *Json) getPointerByPatternWithoutViolenceCheck(pattern string) *interface{} { +func (j *Json) getPointerByPatternWithoutViolenceCheck(pattern string) *any { if j.vc { return j.getPointerByPatternWithViolenceCheck(pattern) } @@ -454,17 +454,17 @@ func (j *Json) getPointerByPatternWithoutViolenceCheck(pattern string) *interfac // checkPatternByPointer checks whether there's value by `key` in specified `pointer`. // It returns a pointer to the value. -func (j *Json) checkPatternByPointer(key string, pointer *interface{}) *interface{} { +func (j *Json) checkPatternByPointer(key string, pointer *any) *any { switch (*pointer).(type) { - case map[string]interface{}: - if v, ok := (*pointer).(map[string]interface{})[key]; ok { + case map[string]any: + if v, ok := (*pointer).(map[string]any)[key]; ok { return &v } - case []interface{}: + case []any: if gstr.IsNumeric(key) { n, err := strconv.Atoi(key) - if err == nil && len((*pointer).([]interface{})) > n { - return &(*pointer).([]interface{})[n] + if err == nil && len((*pointer).([]any)) > n { + return &(*pointer).([]any)[n] } } } diff --git a/encoding/gjson/gjson_api.go b/encoding/gjson/gjson_api.go index 1b7425bd949..63c75ee28ce 100644 --- a/encoding/gjson/gjson_api.go +++ b/encoding/gjson/gjson_api.go @@ -16,7 +16,7 @@ import ( ) // Interface returns the json value. -func (j *Json) Interface() interface{} { +func (j *Json) Interface() any { if j == nil { return nil } @@ -51,7 +51,7 @@ func (j *Json) IsNil() bool { // "list.10", "array.0.name", "array.0.1.id". // // It returns a default value specified by `def` if value for `pattern` is not found. -func (j *Json) Get(pattern string, def ...interface{}) *gvar.Var { +func (j *Json) Get(pattern string, def ...any) *gvar.Var { if j == nil { return nil } @@ -75,13 +75,13 @@ func (j *Json) Get(pattern string, def ...interface{}) *gvar.Var { // GetJson gets the value by specified `pattern`, // and converts it to an un-concurrent-safe Json object. -func (j *Json) GetJson(pattern string, def ...interface{}) *Json { +func (j *Json) GetJson(pattern string, def ...any) *Json { return New(j.Get(pattern, def...).Val()) } // GetJsons gets the value by specified `pattern`, // and converts it to a slice of un-concurrent-safe Json object. -func (j *Json) GetJsons(pattern string, def ...interface{}) []*Json { +func (j *Json) GetJsons(pattern string, def ...any) []*Json { array := j.Get(pattern, def...).Array() if len(array) > 0 { jsonSlice := make([]*Json, len(array)) @@ -95,7 +95,7 @@ func (j *Json) GetJsons(pattern string, def ...interface{}) []*Json { // GetJsonMap gets the value by specified `pattern`, // and converts it to a map of un-concurrent-safe Json object. -func (j *Json) GetJsonMap(pattern string, def ...interface{}) map[string]*Json { +func (j *Json) GetJsonMap(pattern string, def ...any) map[string]*Json { m := j.Get(pattern, def...).Map() if len(m) > 0 { jsonMap := make(map[string]*Json, len(m)) @@ -109,12 +109,12 @@ func (j *Json) GetJsonMap(pattern string, def ...interface{}) map[string]*Json { // Set sets value with specified `pattern`. // It supports hierarchical data access by char separator, which is '.' in default. -func (j *Json) Set(pattern string, value interface{}) error { +func (j *Json) Set(pattern string, value any) error { return j.setValue(pattern, value, false) } // MustSet performs as Set, but it panics if any error occurs. -func (j *Json) MustSet(pattern string, value interface{}) { +func (j *Json) MustSet(pattern string, value any) { if err := j.Set(pattern, value); err != nil { panic(err) } @@ -145,10 +145,10 @@ func (j *Json) Len(pattern string) int { p := j.getPointerByPattern(pattern) if p != nil { switch (*p).(type) { - case map[string]interface{}: - return len((*p).(map[string]interface{})) - case []interface{}: - return len((*p).([]interface{})) + case map[string]any: + return len((*p).(map[string]any)) + case []any: + return len((*p).([]any)) default: return -1 } @@ -158,7 +158,7 @@ func (j *Json) Len(pattern string) int { // Append appends value to the value by specified `pattern`. // The target value by `pattern` should be type of slice. -func (j *Json) Append(pattern string, value interface{}) error { +func (j *Json) Append(pattern string, value any) error { p := j.getPointerByPattern(pattern) if p == nil || *p == nil { if pattern == "." { @@ -167,37 +167,37 @@ func (j *Json) Append(pattern string, value interface{}) error { return j.Set(fmt.Sprintf("%s.0", pattern), value) } switch (*p).(type) { - case []interface{}: + case []any: if pattern == "." { - return j.Set(fmt.Sprintf("%d", len((*p).([]interface{}))), value) + return j.Set(fmt.Sprintf("%d", len((*p).([]any))), value) } - return j.Set(fmt.Sprintf("%s.%d", pattern, len((*p).([]interface{}))), value) + return j.Set(fmt.Sprintf("%s.%d", pattern, len((*p).([]any))), value) } return gerror.NewCodef(gcode.CodeInvalidParameter, "invalid variable type of %s", pattern) } // MustAppend performs as Append, but it panics if any error occurs. -func (j *Json) MustAppend(pattern string, value interface{}) { +func (j *Json) MustAppend(pattern string, value any) { if err := j.Append(pattern, value); err != nil { panic(err) } } -// Map converts current Json object to map[string]interface{}. +// Map converts current Json object to map[string]any. // It returns nil if fails. -func (j *Json) Map() map[string]interface{} { +func (j *Json) Map() map[string]any { return j.Var().Map() } -// Array converts current Json object to []interface{}. +// Array converts current Json object to []any. // It returns nil if fails. -func (j *Json) Array() []interface{} { +func (j *Json) Array() []any { return j.Var().Array() } // Scan automatically calls Struct or Structs function according to the type of parameter // `pointer` to implement the converting. -func (j *Json) Scan(pointer interface{}, mapping ...map[string]string) error { +func (j *Json) Scan(pointer any, mapping ...map[string]string) error { return j.Var().Scan(pointer, mapping...) } diff --git a/encoding/gjson/gjson_api_new_load.go b/encoding/gjson/gjson_api_new_load.go index 48b9538c3df..761584b8b3f 100644 --- a/encoding/gjson/gjson_api_new_load.go +++ b/encoding/gjson/gjson_api_new_load.go @@ -19,7 +19,7 @@ import ( // // The parameter `safe` specifies whether using this Json object in concurrent-safe context, // which is false in default. -func New(data interface{}, safe ...bool) *Json { +func New(data any, safe ...bool) *Json { return NewWithTag(data, string(ContentTypeJSON), safe...) } @@ -31,7 +31,7 @@ func New(data interface{}, safe ...bool) *Json { // // The parameter `safe` specifies whether using this Json object in concurrent-safe context, which // is false in default. -func NewWithTag(data interface{}, tags string, safe ...bool) *Json { +func NewWithTag(data any, tags string, safe ...bool) *Json { option := Options{ Tags: tags, } @@ -43,7 +43,7 @@ func NewWithTag(data interface{}, tags string, safe ...bool) *Json { // NewWithOptions creates a Json object with any variable type of `data`, but `data` should be a map // or slice for data access reason, or it will make no sense. -func NewWithOptions(data interface{}, options Options) *Json { +func NewWithOptions(data any, options Options) *Json { var j *Json switch result := data.(type) { case []byte: @@ -68,7 +68,7 @@ func NewWithOptions(data interface{}, options Options) *Json { } default: var ( - pointedData interface{} + pointedData any reflectInfo = reflection.OriginValueAndKind(data) ) switch reflectInfo.OriginKind { diff --git a/encoding/gjson/gjson_api_new_load_content.go b/encoding/gjson/gjson_api_new_load_content.go index a2329ad87ed..fa102e9107d 100644 --- a/encoding/gjson/gjson_api_new_load_content.go +++ b/encoding/gjson/gjson_api_new_load_content.go @@ -155,7 +155,7 @@ func trimBOM(data []byte) []byte { func loadContentWithOptions(data []byte, options Options) (*Json, error) { var ( err error - result interface{} + result any ) data = trimBOM(data) if len(data) == 0 { diff --git a/encoding/gjson/gjson_implements.go b/encoding/gjson/gjson_implements.go index 377b4f2cace..b671a59c9c9 100644 --- a/encoding/gjson/gjson_implements.go +++ b/encoding/gjson/gjson_implements.go @@ -25,7 +25,7 @@ func (j *Json) UnmarshalJSON(b []byte) error { } // UnmarshalValue is an interface implement which sets any type of value for Json. -func (j *Json) UnmarshalValue(value interface{}) error { +func (j *Json) UnmarshalValue(value any) error { if r := NewWithOptions(value, Options{ StrNumber: true, }); r != nil { @@ -36,7 +36,7 @@ func (j *Json) UnmarshalValue(value interface{}) error { } // MapStrAny implements interface function MapStrAny(). -func (j *Json) MapStrAny() map[string]interface{} { +func (j *Json) MapStrAny() map[string]any { if j == nil { return nil } @@ -44,7 +44,7 @@ func (j *Json) MapStrAny() map[string]interface{} { } // Interfaces implements interface function Interfaces(). -func (j *Json) Interfaces() []interface{} { +func (j *Json) Interfaces() []any { if j == nil { return nil } diff --git a/encoding/gjson/gjson_stdlib_json_util.go b/encoding/gjson/gjson_stdlib_json_util.go index 7ce04b81d2e..91a646f3ebb 100644 --- a/encoding/gjson/gjson_stdlib_json_util.go +++ b/encoding/gjson/gjson_stdlib_json_util.go @@ -17,32 +17,32 @@ import ( // Valid checks whether `data` is a valid JSON data type. // The parameter `data` specifies the json format data, which can be either // bytes or string type. -func Valid(data interface{}) bool { +func Valid(data any) bool { return json.Valid(gconv.Bytes(data)) } // Marshal is alias of Encode in order to fit the habit of json.Marshal/Unmarshal functions. -func Marshal(v interface{}) (marshaledBytes []byte, err error) { +func Marshal(v any) (marshaledBytes []byte, err error) { return Encode(v) } // MarshalIndent is alias of json.MarshalIndent in order to fit the habit of json.MarshalIndent function. -func MarshalIndent(v interface{}, prefix, indent string) (marshaledBytes []byte, err error) { +func MarshalIndent(v any, prefix, indent string) (marshaledBytes []byte, err error) { return json.MarshalIndent(v, prefix, indent) } // Unmarshal is alias of DecodeTo in order to fit the habit of json.Marshal/Unmarshal functions. -func Unmarshal(data []byte, v interface{}) (err error) { +func Unmarshal(data []byte, v any) (err error) { return DecodeTo(data, v) } // Encode encodes any golang variable `value` to JSON bytes. -func Encode(value interface{}) ([]byte, error) { +func Encode(value any) ([]byte, error) { return json.Marshal(value) } // MustEncode performs as Encode, but it panics if any error occurs. -func MustEncode(value interface{}) []byte { +func MustEncode(value any) []byte { b, err := Encode(value) if err != nil { panic(err) @@ -51,21 +51,21 @@ func MustEncode(value interface{}) []byte { } // EncodeString encodes any golang variable `value` to JSON string. -func EncodeString(value interface{}) (string, error) { +func EncodeString(value any) (string, error) { b, err := json.Marshal(value) return string(b), err } // MustEncodeString encodes any golang variable `value` to JSON string. // It panics if any error occurs. -func MustEncodeString(value interface{}) string { +func MustEncodeString(value any) string { return string(MustEncode(value)) } // Decode decodes json format `data` to golang variable. // The parameter `data` can be either bytes or string type. -func Decode(data interface{}, options ...Options) (interface{}, error) { - var value interface{} +func Decode(data any, options ...Options) (any, error) { + var value any if err := DecodeTo(gconv.Bytes(data), &value, options...); err != nil { return nil, err } else { @@ -76,7 +76,7 @@ func Decode(data interface{}, options ...Options) (interface{}, error) { // DecodeTo decodes json format `data` to specified golang variable `v`. // The parameter `data` can be either bytes or string type. // The parameter `v` should be a pointer type. -func DecodeTo(data interface{}, v interface{}, options ...Options) (err error) { +func DecodeTo(data any, v any, options ...Options) (err error) { decoder := json.NewDecoder(bytes.NewReader(gconv.Bytes(data))) if len(options) > 0 { // The StrNumber option is for certain situations, not for all. @@ -93,7 +93,7 @@ func DecodeTo(data interface{}, v interface{}, options ...Options) (err error) { // DecodeToJson codes json format `data` to a Json object. // The parameter `data` can be either bytes or string type. -func DecodeToJson(data interface{}, options ...Options) (*Json, error) { +func DecodeToJson(data any, options ...Options) (*Json, error) { if v, err := Decode(gconv.Bytes(data), options...); err != nil { return nil, err } else { diff --git a/encoding/gjson/gjson_z_bench_test.go b/encoding/gjson/gjson_z_bench_test.go index 7506c1f7de4..5814e97c2b4 100644 --- a/encoding/gjson/gjson_z_bench_test.go +++ b/encoding/gjson/gjson_z_bench_test.go @@ -46,14 +46,14 @@ func Benchmark_Get_Complicated_Json(b *testing.B) { func Benchmark_Stdlib_Json_Unmarshal_Simple_Json(b *testing.B) { for i := 0; i < b.N; i++ { - var m map[string]interface{} + var m map[string]any json2.Unmarshal([]byte(jsonStr1), &m) } } func Benchmark_Stdlib_Json_Unmarshal_Complicated_Json(b *testing.B) { for i := 0; i < b.N; i++ { - var m map[string]interface{} + var m map[string]any json2.Unmarshal([]byte(jsonStr2), &m) } } diff --git a/encoding/gjson/gjson_z_example_conversion_test.go b/encoding/gjson/gjson_z_example_conversion_test.go index 8d461cccade..1ee41dd99b3 100644 --- a/encoding/gjson/gjson_z_example_conversion_test.go +++ b/encoding/gjson/gjson_z_example_conversion_test.go @@ -124,7 +124,7 @@ func ExampleValid() { } func ExampleMarshal() { - data := map[string]interface{}{ + data := map[string]any{ "name": "john", "score": 100, } diff --git a/encoding/gjson/gjson_z_unit_feature_json_test.go b/encoding/gjson/gjson_z_unit_feature_json_test.go index 542b8e795c7..f8ffbba65d6 100644 --- a/encoding/gjson/gjson_z_unit_feature_json_test.go +++ b/encoding/gjson/gjson_z_unit_feature_json_test.go @@ -59,7 +59,7 @@ func Test_MapAttributeConvert(t *testing.T) { gtest.AssertNil(err) tx := struct { - Title map[string]interface{} + Title map[string]any }{} err = j.Var().Scan(&tx) diff --git a/encoding/gjson/gjson_z_unit_feature_struct_test.go b/encoding/gjson/gjson_z_unit_feature_struct_test.go index df13c1b982c..6878eb85f35 100644 --- a/encoding/gjson/gjson_z_unit_feature_struct_test.go +++ b/encoding/gjson/gjson_z_unit_feature_struct_test.go @@ -213,10 +213,10 @@ func Test_Struct(t *testing.T) { } type M struct { - Id string `json:"id"` - Me map[string]interface{} `json:"me"` - Txt string `json:"txt"` - Items []*Item `json:"items"` + Id string `json:"id"` + Me map[string]any `json:"me"` + Txt string `json:"txt"` + Items []*Item `json:"items"` } txt := []byte(` diff --git a/encoding/gjson/gjson_z_unit_test.go b/encoding/gjson/gjson_z_unit_test.go index 9bb6958e5b6..c2e589e6806 100644 --- a/encoding/gjson/gjson_z_unit_test.go +++ b/encoding/gjson/gjson_z_unit_test.go @@ -102,7 +102,7 @@ func Test_Decode(t *testing.T) { }) }) gtest.C(t, func(t *gtest.T) { - var v interface{} + var v any err := gjson.DecodeTo(data, &v) t.AssertNil(err) t.Assert(v, g.Map{ @@ -558,7 +558,7 @@ func TestJson_Options(t *testing.T) { s := S{ Id: 53687091200, } - m := make(map[string]interface{}) + m := make(map[string]any) t.AssertNil(gjson.DecodeTo(gjson.MustEncode(s), &m, gjson.Options{ StrNumber: false, })) diff --git a/encoding/gproperties/gproperties.go b/encoding/gproperties/gproperties.go index 580fe29801c..8ad4ab021bc 100644 --- a/encoding/gproperties/gproperties.go +++ b/encoding/gproperties/gproperties.go @@ -20,8 +20,8 @@ import ( ) // Decode converts properties format to map. -func Decode(data []byte) (res map[string]interface{}, err error) { - res = make(map[string]interface{}) +func Decode(data []byte) (res map[string]any, err error) { + res = make(map[string]any) pr, err := properties.Load(data, properties.UTF8) if err != nil || pr == nil { err = gerror.Wrapf(err, `Lib magiconair load Properties data failed.`) @@ -42,10 +42,10 @@ func Decode(data []byte) (res map[string]interface{}, err error) { } // Encode converts map to properties format. -func Encode(data map[string]interface{}) (res []byte, err error) { +func Encode(data map[string]any) (res []byte, err error) { pr := properties.NewProperties() - flattened := map[string]interface{}{} + flattened := map[string]any{} flattened = flattenAndMergeMap(flattened, data, "", ".") @@ -87,20 +87,20 @@ func ToJson(data []byte) (res []byte, err error) { // deepSearch scans deep maps, following the key indexes listed in the sequence "path". // The last value is expected to be another map, and is returned. -func deepSearch(m map[string]interface{}, path []string) map[string]interface{} { +func deepSearch(m map[string]any, path []string) map[string]any { for _, k := range path { m2, ok := m[k] if !ok { // intermediate key does not exist // => create it and continue from there - m3 := make(map[string]interface{}) + m3 := make(map[string]any) m[k] = m3 m = m3 continue } - m3, ok := m2.(map[string]interface{}) + m3, ok := m2.(map[string]any) if !ok { - m3 = make(map[string]interface{}) + m3 = make(map[string]any) m[k] = m3 } // continue search from here @@ -110,21 +110,21 @@ func deepSearch(m map[string]interface{}, path []string) map[string]interface{} } // flattenAndMergeMap recursively flattens the given map into a new map -func flattenAndMergeMap(shadow map[string]interface{}, m map[string]interface{}, prefix string, delimiter string) map[string]interface{} { +func flattenAndMergeMap(shadow map[string]any, m map[string]any, prefix string, delimiter string) map[string]any { if shadow != nil && prefix != "" && shadow[prefix] != nil { return shadow } - var m2 map[string]interface{} + var m2 map[string]any if prefix != "" { prefix += delimiter } for k, val := range m { fullKey := prefix + k - switch val.(type) { - case map[string]interface{}: - m2 = val.(map[string]interface{}) - case map[interface{}]interface{}: + switch val := val.(type) { + case map[string]any: + m2 = val + case map[any]any: m2 = gconv.Map(val) default: // immediate value diff --git a/encoding/gproperties/gproperties_z_unit_test.go b/encoding/gproperties/gproperties_z_unit_test.go index c23ad27099a..9054a1c3491 100644 --- a/encoding/gproperties/gproperties_z_unit_test.go +++ b/encoding/gproperties/gproperties_z_unit_test.go @@ -50,7 +50,7 @@ var errorTests = []struct { func TestDecode(t *testing.T) { gtest.C(t, func(t *gtest.T) { - m := make(map[string]interface{}) + m := make(map[string]any) m["properties"] = pStr res, err := gproperties.Encode(m) if err != nil { @@ -79,7 +79,7 @@ func TestDecode(t *testing.T) { func TestEncode(t *testing.T) { gtest.C(t, func(t *gtest.T) { - m := make(map[string]interface{}) + m := make(map[string]any) m["properties"] = pStr res, err := gproperties.Encode(m) if err != nil { @@ -97,7 +97,7 @@ func TestEncode(t *testing.T) { func TestToJson(t *testing.T) { gtest.C(t, func(t *gtest.T) { - res, err := gproperties.Encode(map[string]interface{}{ + res, err := gproperties.Encode(map[string]any{ "sql": g.Map{ "userName": "admin", "password": "123456", diff --git a/encoding/gtoml/gtoml.go b/encoding/gtoml/gtoml.go index aeca726bbd1..2c57024b592 100644 --- a/encoding/gtoml/gtoml.go +++ b/encoding/gtoml/gtoml.go @@ -16,7 +16,7 @@ import ( "github.com/gogf/gf/v2/internal/json" ) -func Encode(v interface{}) ([]byte, error) { +func Encode(v any) ([]byte, error) { buffer := bytes.NewBuffer(nil) if err := toml.NewEncoder(buffer).Encode(v); err != nil { err = gerror.Wrap(err, `toml.Encoder.Encode failed`) @@ -25,8 +25,8 @@ func Encode(v interface{}) ([]byte, error) { return buffer.Bytes(), nil } -func Decode(v []byte) (interface{}, error) { - var result interface{} +func Decode(v []byte) (any, error) { + var result any if err := toml.Unmarshal(v, &result); err != nil { err = gerror.Wrap(err, `toml.Unmarshal failed`) return nil, err @@ -34,7 +34,7 @@ func Decode(v []byte) (interface{}, error) { return result, nil } -func DecodeTo(v []byte, result interface{}) (err error) { +func DecodeTo(v []byte, result any) (err error) { err = toml.Unmarshal(v, result) if err != nil { err = gerror.Wrap(err, `toml.Unmarshal failed`) diff --git a/encoding/gtoml/gtoml_z_unit_test.go b/encoding/gtoml/gtoml_z_unit_test.go index aa02421fa24..110c7a3b8a9 100644 --- a/encoding/gtoml/gtoml_z_unit_test.go +++ b/encoding/gtoml/gtoml_z_unit_test.go @@ -68,9 +68,9 @@ func TestDecode(t *testing.T) { return } - t.Assert(decodeStr.(map[string]interface{})["toml"], tomlStr) + t.Assert(decodeStr.(map[string]any)["toml"], tomlStr) - decodeStr1 := make(map[string]interface{}) + decodeStr1 := make(map[string]any) err = gtoml.DecodeTo(res, &decodeStr1) if err != nil { t.Errorf("decodeTo failed. %v", err) @@ -86,7 +86,7 @@ func TestDecode(t *testing.T) { return } - decodeStr1 := make(map[string]interface{}) + decodeStr1 := make(map[string]any) err = gtoml.DecodeTo([]byte(tomlErr), &decodeStr1) if err == nil { t.Errorf("decodeTo failed. %v", err) diff --git a/encoding/gxml/gxml.go b/encoding/gxml/gxml.go index f28d3dbc4a1..a3401eb4dea 100644 --- a/encoding/gxml/gxml.go +++ b/encoding/gxml/gxml.go @@ -18,7 +18,7 @@ import ( ) // Decode parses `content` into and returns as map. -func Decode(content []byte) (map[string]interface{}, error) { +func Decode(content []byte) (map[string]any, error) { res, err := convert(content) if err != nil { return nil, err @@ -31,7 +31,7 @@ func Decode(content []byte) (map[string]interface{}, error) { } // DecodeWithoutRoot parses `content` into a map, and returns the map without root level. -func DecodeWithoutRoot(content []byte) (map[string]interface{}, error) { +func DecodeWithoutRoot(content []byte) (map[string]any, error) { res, err := convert(content) if err != nil { return nil, err @@ -42,7 +42,7 @@ func DecodeWithoutRoot(content []byte) (map[string]interface{}, error) { return nil, err } for _, v := range m { - if r, ok := v.(map[string]interface{}); ok { + if r, ok := v.(map[string]any); ok { return r, nil } } @@ -72,7 +72,7 @@ func XMLEscapeChars(b ...bool) { // Encode encodes map `m` to an XML format content as bytes. // The optional parameter `rootTag` is used to specify the XML root tag. -func Encode(m map[string]interface{}, rootTag ...string) ([]byte, error) { +func Encode(m map[string]any, rootTag ...string) ([]byte, error) { b, err := mxj.Map(m).Xml(rootTag...) if err != nil { err = gerror.Wrapf(err, `mxj.Map.Xml failed`) @@ -82,7 +82,7 @@ func Encode(m map[string]interface{}, rootTag ...string) ([]byte, error) { // EncodeWithIndent encodes map `m` to an XML format content as bytes with indent. // The optional parameter `rootTag` is used to specify the XML root tag. -func EncodeWithIndent(m map[string]interface{}, rootTag ...string) ([]byte, error) { +func EncodeWithIndent(m map[string]any, rootTag ...string) ([]byte, error) { b, err := mxj.Map(m).XmlIndent("", "\t", rootTag...) if err != nil { err = gerror.Wrapf(err, `mxj.Map.XmlIndent failed`) diff --git a/encoding/gxml/gxml_z_unit_test.go b/encoding/gxml/gxml_z_unit_test.go index e519cda8131..f1e161b4d39 100644 --- a/encoding/gxml/gxml_z_unit_test.go +++ b/encoding/gxml/gxml_z_unit_test.go @@ -96,8 +96,8 @@ func Test_Decode1(t *testing.T) { if err != nil { t.Errorf("gxml decode error. %s", dstXml) } - s := srcMap["doc"].(map[string]interface{}) - d := dstMap["doc"].(map[string]interface{}) + s := srcMap["doc"].(map[string]any) + d := dstMap["doc"].(map[string]any) for kk, vv := range s { if vv.(string) != d[kk].(string) { t.Errorf("convert to map error. src:%v, dst:%v", vv, d[kk]) @@ -113,9 +113,9 @@ func Test_Decode2(t *testing.T) { ` m, err := gxml.Decode([]byte(content)) t.AssertNil(err) - t.Assert(m["doc"].(map[string]interface{})["username"], "johngcn") - t.Assert(m["doc"].(map[string]interface{})["password1"], "123456") - t.Assert(m["doc"].(map[string]interface{})["password2"], "123456") + t.Assert(m["doc"].(map[string]any)["username"], "johngcn") + t.Assert(m["doc"].(map[string]any)["password1"], "123456") + t.Assert(m["doc"].(map[string]any)["password2"], "123456") }) } @@ -133,14 +133,14 @@ func Test_DecodeWitoutRoot(t *testing.T) { } func Test_Encode(t *testing.T) { - m := make(map[string]interface{}) - v := map[string]interface{}{ + m := make(map[string]any) + v := map[string]any{ "string": "hello world", "int": 123, "float": 100.92, "bool": true, } - m["root"] = interface{}(v) + m["root"] = any(v) xmlStr, err := gxml.Encode(m) if err != nil { @@ -155,14 +155,14 @@ func Test_Encode(t *testing.T) { } func Test_EncodeIndent(t *testing.T) { - m := make(map[string]interface{}) - v := map[string]interface{}{ + m := make(map[string]any) + v := map[string]any{ "string": "hello world", "int": 123, "float": 100.92, "bool": true, } - m["root"] = interface{}(v) + m["root"] = any(v) _, err := gxml.EncodeWithIndent(m, "xml") if err != nil { @@ -211,8 +211,8 @@ func Test_Issue3716(t *testing.T) { gtest.C(t, func(t *gtest.T) { var ( xml = `I am a software developer & I love coding.john.doe@example.com<>&'"AAA` - m = map[string]interface{}{ - "Person": map[string]interface{}{ + m = map[string]any{ + "Person": map[string]any{ "Name": "<>&'\"AAA", "Email": "john.doe@example.com", "Bio": "I am a software developer & I love coding.", diff --git a/encoding/gyaml/gyaml.go b/encoding/gyaml/gyaml.go index 00aa915541d..720ca569c58 100644 --- a/encoding/gyaml/gyaml.go +++ b/encoding/gyaml/gyaml.go @@ -19,7 +19,7 @@ import ( ) // Encode encodes `value` to an YAML format content as bytes. -func Encode(value interface{}) (out []byte, err error) { +func Encode(value any) (out []byte, err error) { if out, err = yaml.Marshal(value); err != nil { err = gerror.Wrap(err, `yaml.Marshal failed`) } @@ -27,7 +27,7 @@ func Encode(value interface{}) (out []byte, err error) { } // EncodeIndent encodes `value` to an YAML format content with indent as bytes. -func EncodeIndent(value interface{}, indent string) (out []byte, err error) { +func EncodeIndent(value any, indent string) (out []byte, err error) { out, err = Encode(value) if err != nil { return @@ -48,9 +48,9 @@ func EncodeIndent(value interface{}, indent string) (out []byte, err error) { } // Decode parses `content` into and returns as map. -func Decode(content []byte) (map[string]interface{}, error) { +func Decode(content []byte) (map[string]any, error) { var ( - result map[string]interface{} + result map[string]any err error ) if err = yaml.Unmarshal(content, &result); err != nil { @@ -61,7 +61,7 @@ func Decode(content []byte) (map[string]interface{}, error) { } // DecodeTo parses `content` into `result`. -func DecodeTo(value []byte, result interface{}) (err error) { +func DecodeTo(value []byte, result any) (err error) { err = yaml.Unmarshal(value, result) if err != nil { err = gerror.Wrap(err, `yaml.Unmarshal failed`) @@ -72,7 +72,7 @@ func DecodeTo(value []byte, result interface{}) (err error) { // ToJson converts `content` to JSON format content. func ToJson(content []byte) (out []byte, err error) { var ( - result interface{} + result any ) if result, err = Decode(content); err != nil { return nil, err diff --git a/encoding/gyaml/gyaml_z_unit_test.go b/encoding/gyaml/gyaml_z_unit_test.go index cea2fac102a..8fccbe68d0c 100644 --- a/encoding/gyaml/gyaml_z_unit_test.go +++ b/encoding/gyaml/gyaml_z_unit_test.go @@ -76,7 +76,7 @@ func Test_Decode(t *testing.T) { result, err := gyaml.Decode([]byte(yamlStr)) t.AssertNil(err) - t.Assert(result, map[string]interface{}{ + t.Assert(result, map[string]any{ "url": "https://goframe.org", "server": g.Slice{"120.168.117.21", "120.168.117.22"}, "pi": 3.14, @@ -88,10 +88,10 @@ func Test_Decode(t *testing.T) { func Test_DecodeTo(t *testing.T) { gtest.C(t, func(t *gtest.T) { - result := make(map[string]interface{}) + result := make(map[string]any) err := gyaml.DecodeTo([]byte(yamlStr), &result) t.AssertNil(err) - t.Assert(result, map[string]interface{}{ + t.Assert(result, map[string]any{ "url": "https://goframe.org", "server": g.Slice{"120.168.117.21", "120.168.117.22"}, "pi": 3.14, @@ -106,7 +106,7 @@ func Test_DecodeError(t *testing.T) { _, err := gyaml.Decode([]byte(yamlErr)) t.AssertNE(err, nil) - result := make(map[string]interface{}) + result := make(map[string]any) err = gyaml.DecodeTo([]byte(yamlErr), &result) t.AssertNE(err, nil) }) @@ -143,10 +143,6 @@ func Test_ToJson(t *testing.T) { } p := gjson.New(res) - if err != nil { - t.Errorf("parser failed. %v", err) - return - } expectJson, err := p.ToJson() if err != nil { t.Errorf("parser ToJson failed. %v", err) diff --git a/errors/gcode/gcode.go b/errors/gcode/gcode.go index bbbf0e8755d..88db12bd3e6 100644 --- a/errors/gcode/gcode.go +++ b/errors/gcode/gcode.go @@ -17,7 +17,7 @@ type Code interface { // Detail returns the detailed information of current error code, // which is mainly designed as an extension field for error code. - Detail() interface{} + Detail() any } // ================================================================================================================ @@ -52,7 +52,7 @@ var ( // New creates and returns an error code. // Note that it returns an interface object of Code. -func New(code int, message string, detail interface{}) Code { +func New(code int, message string, detail any) Code { return localCode{ code: code, message: message, @@ -62,7 +62,7 @@ func New(code int, message string, detail interface{}) Code { // WithCode creates and returns a new error code based on given Code. // The code and message is from given `code`, but the detail if from given `detail`. -func WithCode(code Code, detail interface{}) Code { +func WithCode(code Code, detail any) Code { return localCode{ code: code.Code(), message: code.Message(), diff --git a/errors/gcode/gcode_local.go b/errors/gcode/gcode_local.go index 1ec1d1ea99f..43bbec8de25 100644 --- a/errors/gcode/gcode_local.go +++ b/errors/gcode/gcode_local.go @@ -10,9 +10,9 @@ import "fmt" // localCode is an implementer for interface Code for internal usage only. type localCode struct { - code int // Error code, usually an integer. - message string // Brief message for this error code. - detail interface{} // As type of interface, it is mainly designed as an extension field for error code. + code int // Error code, usually an integer. + message string // Brief message for this error code. + detail any // As type of interface, it is mainly designed as an extension field for error code. } // Code returns the integer number of current error code. @@ -27,7 +27,7 @@ func (c localCode) Message() string { // Detail returns the detailed information of current error code, // which is mainly designed as an extension field for error code. -func (c localCode) Detail() interface{} { +func (c localCode) Detail() any { return c.detail } diff --git a/errors/gerror/gerror_api.go b/errors/gerror/gerror_api.go index 9f6a8c9e3d1..3b2b3915f5f 100644 --- a/errors/gerror/gerror_api.go +++ b/errors/gerror/gerror_api.go @@ -22,7 +22,7 @@ func New(text string) error { } // Newf returns an error that formats as the given format and args. -func Newf(format string, args ...interface{}) error { +func Newf(format string, args ...any) error { return &Error{ stack: callers(), text: fmt.Sprintf(format, args...), @@ -42,7 +42,7 @@ func NewSkip(skip int, text string) error { // NewSkipf returns an error that formats as the given format and args. // The parameter `skip` specifies the stack callers skipped amount. -func NewSkipf(skip int, format string, args ...interface{}) error { +func NewSkipf(skip int, format string, args ...any) error { return &Error{ stack: callers(skip), text: fmt.Sprintf(format, args...), @@ -67,7 +67,7 @@ func Wrap(err error, text string) error { // Wrapf returns an error annotating err with a stack trace at the point Wrapf is called, and the format specifier. // It returns nil if given `err` is nil. // Note that it does not lose the error code of wrapped error, as it inherits the error code from it. -func Wrapf(err error, format string, args ...interface{}) error { +func Wrapf(err error, format string, args ...any) error { if err == nil { return nil } @@ -97,7 +97,7 @@ func WrapSkip(skip int, err error, text string) error { // WrapSkipf wraps error with text that is formatted with given format and args. It returns nil if given err is nil. // The parameter `skip` specifies the stack callers skipped amount. // Note that it does not lose the error code of wrapped error, as it inherits the error code from it. -func WrapSkipf(skip int, err error, format string, args ...interface{}) error { +func WrapSkipf(skip int, err error, format string, args ...any) error { if err == nil { return nil } diff --git a/errors/gerror/gerror_api_code.go b/errors/gerror/gerror_api_code.go index 98ac328214f..c13305ca8b7 100644 --- a/errors/gerror/gerror_api_code.go +++ b/errors/gerror/gerror_api_code.go @@ -23,7 +23,7 @@ func NewCode(code gcode.Code, text ...string) error { } // NewCodef returns an error that has error code and formats as the given format and args. -func NewCodef(code gcode.Code, format string, args ...interface{}) error { +func NewCodef(code gcode.Code, format string, args ...any) error { return &Error{ stack: callers(), text: fmt.Sprintf(format, args...), @@ -43,7 +43,7 @@ func NewCodeSkip(code gcode.Code, skip int, text ...string) error { // NewCodeSkipf returns an error that has error code and formats as the given format and args. // The parameter `skip` specifies the stack callers skipped amount. -func NewCodeSkipf(code gcode.Code, skip int, format string, args ...interface{}) error { +func NewCodeSkipf(code gcode.Code, skip int, format string, args ...any) error { return &Error{ stack: callers(skip), text: fmt.Sprintf(format, args...), @@ -67,7 +67,7 @@ func WrapCode(code gcode.Code, err error, text ...string) error { // WrapCodef wraps error with code and format specifier. // It returns nil if given `err` is nil. -func WrapCodef(code gcode.Code, err error, format string, args ...interface{}) error { +func WrapCodef(code gcode.Code, err error, format string, args ...any) error { if err == nil { return nil } @@ -97,7 +97,7 @@ func WrapCodeSkip(code gcode.Code, skip int, err error, text ...string) error { // WrapCodeSkipf wraps error with code and text that is formatted with given format and args. // It returns nil if given err is nil. // The parameter `skip` specifies the stack callers skipped amount. -func WrapCodeSkipf(code gcode.Code, skip int, err error, format string, args ...interface{}) error { +func WrapCodeSkipf(code gcode.Code, skip int, err error, format string, args ...any) error { if err == nil { return nil } diff --git a/errors/gerror/gerror_api_stack.go b/errors/gerror/gerror_api_stack.go index f773681047c..5caa511728e 100644 --- a/errors/gerror/gerror_api_stack.go +++ b/errors/gerror/gerror_api_stack.go @@ -105,7 +105,7 @@ func Is(err, target error) bool { // repeatedly calling Unwrap. // // An error matches target if the error's concrete value is assignable to the value -// pointed to by target, or if the error has a method As(interface{}) bool such that +// pointed to by target, or if the error has a method As(any) bool such that // As(target) returns true. In the latter case, the As method is responsible for // setting target. // diff --git a/frame/g/g.go b/frame/g/g.go index 5c196c5cbf5..2c6c05381c3 100644 --- a/frame/g/g.go +++ b/frame/g/g.go @@ -24,19 +24,19 @@ type ( ) type ( - Map = map[string]interface{} // Map is alias of frequently-used map type map[string]interface{}. - MapAnyAny = map[interface{}]interface{} // MapAnyAny is alias of frequently-used map type map[interface{}]interface{}. - MapAnyStr = map[interface{}]string // MapAnyStr is alias of frequently-used map type map[interface{}]string. - MapAnyInt = map[interface{}]int // MapAnyInt is alias of frequently-used map type map[interface{}]int. - MapStrAny = map[string]interface{} // MapStrAny is alias of frequently-used map type map[string]interface{}. - MapStrStr = map[string]string // MapStrStr is alias of frequently-used map type map[string]string. - MapStrInt = map[string]int // MapStrInt is alias of frequently-used map type map[string]int. - MapIntAny = map[int]interface{} // MapIntAny is alias of frequently-used map type map[int]interface{}. - MapIntStr = map[int]string // MapIntStr is alias of frequently-used map type map[int]string. - MapIntInt = map[int]int // MapIntInt is alias of frequently-used map type map[int]int. - MapAnyBool = map[interface{}]bool // MapAnyBool is alias of frequently-used map type map[interface{}]bool. - MapStrBool = map[string]bool // MapStrBool is alias of frequently-used map type map[string]bool. - MapIntBool = map[int]bool // MapIntBool is alias of frequently-used map type map[int]bool. + Map = map[string]any // Map is alias of frequently-used map type map[string]any. + MapAnyAny = map[any]any // MapAnyAny is alias of frequently-used map type map[any]any. + MapAnyStr = map[any]string // MapAnyStr is alias of frequently-used map type map[any]string. + MapAnyInt = map[any]int // MapAnyInt is alias of frequently-used map type map[any]int. + MapStrAny = map[string]any // MapStrAny is alias of frequently-used map type map[string]any. + MapStrStr = map[string]string // MapStrStr is alias of frequently-used map type map[string]string. + MapStrInt = map[string]int // MapStrInt is alias of frequently-used map type map[string]int. + MapIntAny = map[int]any // MapIntAny is alias of frequently-used map type map[int]any. + MapIntStr = map[int]string // MapIntStr is alias of frequently-used map type map[int]string. + MapIntInt = map[int]int // MapIntInt is alias of frequently-used map type map[int]int. + MapAnyBool = map[any]bool // MapAnyBool is alias of frequently-used map type map[any]bool. + MapStrBool = map[string]bool // MapStrBool is alias of frequently-used map type map[string]bool. + MapIntBool = map[int]bool // MapIntBool is alias of frequently-used map type map[int]bool. ) type ( @@ -56,15 +56,15 @@ type ( ) type ( - Slice = []interface{} // Slice is alias of frequently-used slice type []interface{}. - SliceAny = []interface{} // SliceAny is alias of frequently-used slice type []interface{}. - SliceStr = []string // SliceStr is alias of frequently-used slice type []string. - SliceInt = []int // SliceInt is alias of frequently-used slice type []int. + Slice = []any // Slice is alias of frequently-used slice type []any. + SliceAny = []any // SliceAny is alias of frequently-used slice type []any. + SliceStr = []string // SliceStr is alias of frequently-used slice type []string. + SliceInt = []int // SliceInt is alias of frequently-used slice type []int. ) type ( - Array = []interface{} // Array is alias of frequently-used slice type []interface{}. - ArrayAny = []interface{} // ArrayAny is alias of frequently-used slice type []interface{}. - ArrayStr = []string // ArrayStr is alias of frequently-used slice type []string. - ArrayInt = []int // ArrayInt is alias of frequently-used slice type []int. + Array = []any // Array is alias of frequently-used slice type []any. + ArrayAny = []any // ArrayAny is alias of frequently-used slice type []any. + ArrayStr = []string // ArrayStr is alias of frequently-used slice type []string. + ArrayInt = []int // ArrayInt is alias of frequently-used slice type []int. ) diff --git a/frame/g/g_func.go b/frame/g/g_func.go index 3aba335703f..e23021b03bd 100644 --- a/frame/g/g_func.go +++ b/frame/g/g_func.go @@ -33,7 +33,7 @@ func Go( } // NewVar returns a gvar.Var. -func NewVar(i interface{}, safe ...bool) *Var { +func NewVar(i any, safe ...bool) *Var { return gvar.New(i, safe...) } @@ -51,23 +51,23 @@ func Listen() { } // Dump dumps a variable to stdout with more manually readable. -func Dump(values ...interface{}) { +func Dump(values ...any) { gutil.Dump(values...) } // DumpTo writes variables `values` as a string in to `writer` with more manually readable -func DumpTo(writer io.Writer, value interface{}, option gutil.DumpOption) { +func DumpTo(writer io.Writer, value any, option gutil.DumpOption) { gutil.DumpTo(writer, value, option) } // DumpWithType acts like Dump, but with type information. // Also see Dump. -func DumpWithType(values ...interface{}) { +func DumpWithType(values ...any) { gutil.DumpWithType(values...) } // DumpWithOption returns variables `values` as a string with more manually readable. -func DumpWithOption(value interface{}, option gutil.DumpOption) { +func DumpWithOption(value any, option gutil.DumpOption) { gutil.DumpWithOption(value, option) } @@ -77,7 +77,7 @@ func DumpJson(value any) { } // Throw throws an exception, which can be caught by TryCatch function. -func Throw(exception interface{}) { +func Throw(exception any) { gutil.Throw(exception) } @@ -100,7 +100,7 @@ func TryCatch(ctx context.Context, try func(ctx context.Context), catch func(ctx // of pointer that also points to a pointer. It returns nil if the source is nil when `traceSource` // is true. // Note that it might use reflect feature which affects performance a little. -func IsNil(value interface{}, traceSource ...bool) bool { +func IsNil(value any, traceSource ...bool) bool { return empty.IsNil(value, traceSource...) } @@ -111,7 +111,7 @@ func IsNil(value interface{}, traceSource ...bool) bool { // The parameter `traceSource` is used for tracing to the source variable if given `value` is type of pointer // that also points to a pointer. It returns true if the source is empty when `traceSource` is true. // Note that it might use reflect feature which affects performance a little. -func IsEmpty(value interface{}, traceSource ...bool) bool { +func IsEmpty(value any, traceSource ...bool) bool { return empty.IsEmpty(value, traceSource...) } diff --git a/frame/g/g_object.go b/frame/g/g_object.go index 86fd9700466..d09e75f6520 100644 --- a/frame/g/g_object.go +++ b/frame/g/g_object.go @@ -28,17 +28,17 @@ func Client() *gclient.Client { } // Server returns an instance of http server with specified name. -func Server(name ...interface{}) *ghttp.Server { +func Server(name ...any) *ghttp.Server { return gins.Server(name...) } // TCPServer returns an instance of tcp server with specified name. -func TCPServer(name ...interface{}) *gtcp.Server { +func TCPServer(name ...any) *gtcp.Server { return gtcp.GetServer(name...) } // UDPServer returns an instance of udp server with specified name. -func UDPServer(name ...interface{}) *gudp.Server { +func UDPServer(name ...any) *gudp.Server { return gudp.GetServer(name...) } @@ -88,12 +88,12 @@ func DB(name ...string) gdb.DB { } // Model creates and returns a model based on configuration of default database group. -func Model(tableNameOrStruct ...interface{}) *gdb.Model { +func Model(tableNameOrStruct ...any) *gdb.Model { return DB().Model(tableNameOrStruct...) } // ModelRaw creates and returns a model based on a raw sql not a table. -func ModelRaw(rawSql string, args ...interface{}) *gdb.Model { +func ModelRaw(rawSql string, args ...any) *gdb.Model { return DB().Raw(rawSql, args...) } diff --git a/frame/gins/gins_database.go b/frame/gins/gins_database.go index ef8e07aafdf..dd04fda10c3 100644 --- a/frame/gins/gins_database.go +++ b/frame/gins/gins_database.go @@ -34,10 +34,10 @@ func Database(name ...string) gdb.DB { group = name[0] } instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameDatabase, group) - db := instance.GetOrSetFuncLock(instanceKey, func() interface{} { + db := instance.GetOrSetFuncLock(instanceKey, func() any { // It ignores returned error to avoid file no found error while it's not necessary. var ( - configMap map[string]interface{} + configMap map[string]any configNodeKey = consts.ConfigNodeNameDatabase ) // It firstly searches the configuration of the instance name. @@ -71,19 +71,19 @@ func Database(name ...string) gdb.DB { } if len(configMap) == 0 { - configMap = make(map[string]interface{}) + configMap = make(map[string]any) } // Parse `m` as map-slice and adds it to global configurations for package gdb. for g, groupConfig := range configMap { cg := gdb.ConfigGroup{} switch value := groupConfig.(type) { - case []interface{}: + case []any: for _, v := range value { if node := parseDBConfigNode(v); node != nil { cg = append(cg, *node) } } - case map[string]interface{}: + case map[string]any: if node := parseDBConfigNode(value); node != nil { cg = append(cg, *node) } @@ -128,7 +128,7 @@ func Database(name ...string) gdb.DB { if db, err := gdb.NewByGroup(name...); err == nil { // Initialize logger for ORM. var ( - loggerConfigMap map[string]interface{} + loggerConfigMap map[string]any loggerNodeName = fmt.Sprintf("%s.%s", configNodeKey, consts.ConfigNodeNameLogger) ) if v, _ := Config().Get(ctx, loggerNodeName); !v.IsEmpty() { @@ -151,7 +151,6 @@ func Database(name ...string) gdb.DB { // If panics, often because it does not find its configuration for given group. panic(err) } - return nil }) if db != nil { return db.(gdb.DB) @@ -159,8 +158,8 @@ func Database(name ...string) gdb.DB { return nil } -func parseDBConfigNode(value interface{}) *gdb.ConfigNode { - nodeMap, ok := value.(map[string]interface{}) +func parseDBConfigNode(value any) *gdb.ConfigNode { + nodeMap, ok := value.(map[string]any) if !ok { return nil } diff --git a/frame/gins/gins_httpclient.go b/frame/gins/gins_httpclient.go index c3fb70d2fea..a8d78502cf0 100644 --- a/frame/gins/gins_httpclient.go +++ b/frame/gins/gins_httpclient.go @@ -14,9 +14,9 @@ import ( ) // HttpClient returns an instance of http client with specified name. -func HttpClient(name ...interface{}) *gclient.Client { +func HttpClient(name ...any) *gclient.Client { var instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameHttpClient, name) - return instance.GetOrSetFuncLock(instanceKey, func() interface{} { + return instance.GetOrSetFuncLock(instanceKey, func() any { return gclient.New() }).(*gclient.Client) } diff --git a/frame/gins/gins_log.go b/frame/gins/gins_log.go index bc1889f4ad4..67822bac7b8 100644 --- a/frame/gins/gins_log.go +++ b/frame/gins/gins_log.go @@ -28,11 +28,11 @@ func Log(name ...string) *glog.Logger { instanceName = name[0] } instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameLogger, instanceName) - return instance.GetOrSetFuncLock(instanceKey, func() interface{} { + return instance.GetOrSetFuncLock(instanceKey, func() any { logger := glog.Instance(instanceName) // To avoid file no found error while it's not necessary. var ( - configMap map[string]interface{} + configMap map[string]any loggerNodeName = consts.ConfigNodeNameLogger ) // Try to find possible `loggerNodeName` in case-insensitive way. diff --git a/frame/gins/gins_redis.go b/frame/gins/gins_redis.go index 7dc36d1a850..4919a329e23 100644 --- a/frame/gins/gins_redis.go +++ b/frame/gins/gins_redis.go @@ -32,14 +32,14 @@ func Redis(name ...string) *gredis.Redis { group = name[0] } instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameRedis, group) - result := instance.GetOrSetFuncLock(instanceKey, func() interface{} { + result := instance.GetOrSetFuncLock(instanceKey, func() any { // If already configured, it returns the redis instance. if _, ok := gredis.GetConfig(group); ok { return gredis.Instance(group) } if Config().Available(ctx) { var ( - configMap map[string]interface{} + configMap map[string]any redisConfig *gredis.Config redisClient *gredis.Redis ) @@ -69,7 +69,6 @@ func Redis(name ...string) *gredis.Redis { gcode.CodeMissingConfiguration, `no configuration found for creating redis client`, )) - return nil }) if result != nil { return result.(*gredis.Redis) diff --git a/frame/gins/gins_server.go b/frame/gins/gins_server.go index dba6f67db73..ea240c1437a 100644 --- a/frame/gins/gins_server.go +++ b/frame/gins/gins_server.go @@ -20,7 +20,7 @@ import ( // Server returns an instance of http server with specified name. // Note that it panics if any error occurs duration instance creating. -func Server(name ...interface{}) *ghttp.Server { +func Server(name ...any) *ghttp.Server { var ( err error ctx = context.Background() @@ -30,14 +30,14 @@ func Server(name ...interface{}) *ghttp.Server { if len(name) > 0 && name[0] != "" { instanceName = gconv.String(name[0]) } - return instance.GetOrSetFuncLock(instanceKey, func() interface{} { + return instance.GetOrSetFuncLock(instanceKey, func() any { server := ghttp.GetServer(instanceName) if Config().Available(ctx) { // Server initialization from configuration. var ( - configMap map[string]interface{} - serverConfigMap map[string]interface{} - serverLoggerConfigMap map[string]interface{} + configMap map[string]any + serverConfigMap map[string]any + serverLoggerConfigMap map[string]any configNodeName string ) if configMap, err = Config().Data(ctx); err != nil { diff --git a/frame/gins/gins_view.go b/frame/gins/gins_view.go index e9d166d8280..74cfdb0a59c 100644 --- a/frame/gins/gins_view.go +++ b/frame/gins/gins_view.go @@ -26,7 +26,7 @@ func View(name ...string) *gview.View { instanceName = name[0] } instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameViewer, instanceName) - return instance.GetOrSetFuncLock(instanceKey, func() interface{} { + return instance.GetOrSetFuncLock(instanceKey, func() any { return getViewInstance(instanceName) }).(*gview.View) } @@ -43,7 +43,7 @@ func getViewInstance(name ...string) *gview.View { view := gview.Instance(instanceName) if Config().Available(ctx) { var ( - configMap map[string]interface{} + configMap map[string]any configNodeName = consts.ConfigNodeNameViewer ) if configMap, err = Config().Data(ctx); err != nil { diff --git a/frame/gins/gins_z_unit_view_test.go b/frame/gins/gins_z_unit_view_test.go index 5a713e5b79d..9f7f5d703a2 100644 --- a/frame/gins/gins_z_unit_view_test.go +++ b/frame/gins/gins_z_unit_view_test.go @@ -65,7 +65,7 @@ func Test_View_Config(t *testing.T) { t.AssertNil(err) str := `hello ${.name},version:${.version}` - view.Assigns(map[string]interface{}{"version": "1.9.0"}) + view.Assigns(map[string]any{"version": "1.9.0"}) result, err := view.ParseContent(ctx, str, nil) t.AssertNil(err) t.Assert(result, "hello test1,version:1.9.0") @@ -87,7 +87,7 @@ func Test_View_Config(t *testing.T) { t.AssertNil(err) str := `hello #{.name},version:#{.version}` - view.Assigns(map[string]interface{}{"version": "1.9.0"}) + view.Assigns(map[string]any{"version": "1.9.0"}) result, err := view.ParseContent(context.TODO(), str, nil) t.AssertNil(err) t.Assert(result, "hello test2,version:1.9.0") @@ -109,7 +109,7 @@ func Test_View_Config(t *testing.T) { t.AssertNil(err) str := `hello {.name},version:{.version}` - view.Assigns(map[string]interface{}{"version": "1.9.0"}) + view.Assigns(map[string]any{"version": "1.9.0"}) result, err := view.ParseContent(context.TODO(), str, nil) t.AssertNil(err) t.Assert(result, "hello test,version:1.9.0") @@ -131,7 +131,7 @@ func Test_View_Config(t *testing.T) { t.AssertNil(err) str := `hello {.name},version:{.version}` - view.Assigns(map[string]interface{}{"version": "1.9.0"}) + view.Assigns(map[string]any{"version": "1.9.0"}) result, err := view.ParseContent(context.TODO(), str, nil) t.AssertNil(err) t.Assert(result, "hello test,version:1.9.0") diff --git a/i18n/gi18n/gi18n.go b/i18n/gi18n/gi18n.go index 09b78f11416..2ad9d3d293e 100644 --- a/i18n/gi18n/gi18n.go +++ b/i18n/gi18n/gi18n.go @@ -30,13 +30,13 @@ func T(ctx context.Context, content string) string { } // Tf is alias of TranslateFormat for convenience. -func Tf(ctx context.Context, format string, values ...interface{}) string { +func Tf(ctx context.Context, format string, values ...any) string { return Instance().TranslateFormat(ctx, format, values...) } // TranslateFormat translates, formats and returns the `format` with configured language // and given `values`. -func TranslateFormat(ctx context.Context, format string, values ...interface{}) string { +func TranslateFormat(ctx context.Context, format string, values ...any) string { return Instance().TranslateFormat(ctx, format, values...) } diff --git a/i18n/gi18n/gi18n_instance.go b/i18n/gi18n/gi18n_instance.go index 58505b94897..8a41c34ad18 100644 --- a/i18n/gi18n/gi18n_instance.go +++ b/i18n/gi18n/gi18n_instance.go @@ -26,7 +26,7 @@ func Instance(name ...string) *Manager { if len(name) > 0 && name[0] != "" { key = name[0] } - return instances.GetOrSetFuncLock(key, func() interface{} { + return instances.GetOrSetFuncLock(key, func() any { return New() }).(*Manager) } diff --git a/i18n/gi18n/gi18n_manager.go b/i18n/gi18n/gi18n_manager.go index 20d90340564..6c126d09c8e 100644 --- a/i18n/gi18n/gi18n_manager.go +++ b/i18n/gi18n/gi18n_manager.go @@ -160,13 +160,13 @@ func (m *Manager) T(ctx context.Context, content string) string { } // Tf is alias of TranslateFormat for convenience. -func (m *Manager) Tf(ctx context.Context, format string, values ...interface{}) string { +func (m *Manager) Tf(ctx context.Context, format string, values ...any) string { return m.TranslateFormat(ctx, format, values...) } // TranslateFormat translates, formats and returns the `format` with configured language // and given `values`. -func (m *Manager) TranslateFormat(ctx context.Context, format string, values ...interface{}) string { +func (m *Manager) TranslateFormat(ctx context.Context, format string, values ...any) string { return fmt.Sprintf(m.Translate(ctx, format), values...) } diff --git a/internal/deepcopy/deepcopy.go b/internal/deepcopy/deepcopy.go index e379f5fd135..0fffb01dbdc 100644 --- a/internal/deepcopy/deepcopy.go +++ b/internal/deepcopy/deepcopy.go @@ -16,13 +16,13 @@ import ( // Interface for delegating copy process to type type Interface interface { - DeepCopy() interface{} + DeepCopy() any } // Copy creates a deep copy of whatever is passed to it and returns the copy -// in an interface{}. The returned value will need to be asserted to the +// in an any. The returned value will need to be asserted to the // correct type. -func Copy(src interface{}) interface{} { +func Copy(src any) any { if src == nil { return nil } @@ -66,7 +66,7 @@ func copyRecursive(original, cpy reflect.Value) { // handle according to original's Kind switch original.Kind() { - case reflect.Ptr: + case reflect.Pointer: // Get the actual value being pointed to. originalValue := original.Elem() diff --git a/internal/deepcopy/deepcopy_test.go b/internal/deepcopy/deepcopy_test.go index fa3e4a1871d..a985b140047 100644 --- a/internal/deepcopy/deepcopy_test.go +++ b/internal/deepcopy/deepcopy_test.go @@ -112,19 +112,19 @@ CopyFloat32s: } CopyInterfaces: - Interfaces := []interface{}{"a", 42, true, 4.32} - cpyIf := Copy(Interfaces).([]interface{}) + Interfaces := []any{"a", 42, true, 4.32} + cpyIf := Copy(Interfaces).([]any) if (*reflect.SliceHeader)(unsafe.Pointer(&Strings)).Data == (*reflect.SliceHeader)(unsafe.Pointer(&cpyIf)).Data { t.Error("[]interfaces: expected SliceHeader data pointers to point to different locations, they didn't") return } if len(cpyIf) != len(Interfaces) { - t.Errorf("[]interface{}: len was %d; want %d", len(cpyIf), len(Interfaces)) + t.Errorf("[]any: len was %d; want %d", len(cpyIf), len(Interfaces)) return } for i, v := range Interfaces { if v != cpyIf[i] { - t.Errorf("[]interface{}: got %v at index %d of the copy; want %v", cpyIf[i], i, v) + t.Errorf("[]any: got %v at index %d of the copy; want %v", cpyIf[i], i, v) } } } @@ -165,8 +165,8 @@ type Basics struct { Complex64s []complex64 Complex128 complex128 Complex128s []complex128 - Interface interface{} - Interfaces []interface{} + Interface any + Interfaces []any } // These tests test that all supported basic types are copied correctly. This @@ -208,7 +208,7 @@ func TestMostTypes(t *testing.T) { Complex64s: []complex64{complex64(-65 + 11i), complex64(66 + 10i)}, Complex128: complex128(-128 + 12i), Complex128s: []complex128{complex128(-128 + 11i), complex128(129 + 10i)}, - Interfaces: []interface{}{42, true, "pan-galactic"}, + Interfaces: []any{42, true, "pan-galactic"}, } cpy := Copy(test).(Basics) @@ -1087,7 +1087,7 @@ type I struct { A string } -func (i *I) DeepCopy() interface{} { +func (i *I) DeepCopy() any { return &I{A: "custom copy"} } diff --git a/internal/empty/empty.go b/internal/empty/empty.go index 5ca3d3b7edd..1db709af5bc 100644 --- a/internal/empty/empty.go +++ b/internal/empty/empty.go @@ -21,12 +21,12 @@ type iString interface { // iInterfaces is used for type assert api for Interfaces. type iInterfaces interface { - Interfaces() []interface{} + Interfaces() []any } // iMapStrAny is the interface support for converting struct parameter to map. type iMapStrAny interface { - MapStrAny() map[string]interface{} + MapStrAny() map[string]any } type iTime interface { @@ -41,7 +41,7 @@ type iTime interface { // The parameter `traceSource` is used for tracing to the source variable if given `value` is type of pointer // that also points to a pointer. It returns true if the source is empty when `traceSource` is true. // Note that it might use reflect feature which affects performance a little. -func IsEmpty(value interface{}, traceSource ...bool) bool { +func IsEmpty(value any, traceSource ...bool) bool { if value == nil { return true } @@ -88,7 +88,7 @@ func IsEmpty(value interface{}, traceSource ...bool) bool { return len(result) == 0 case []float64: return len(result) == 0 - case map[string]interface{}: + case map[string]any: return len(result) == 0 default: @@ -161,7 +161,7 @@ func IsEmpty(value interface{}, traceSource ...bool) bool { return rv.Len() == 0 case reflect.Struct: - var fieldValueInterface interface{} + var fieldValueInterface any for i := 0; i < rv.NumField(); i++ { fieldValueInterface, _ = reflection.ValueToInterface(rv.Field(i)) if !IsEmpty(fieldValueInterface) { @@ -177,7 +177,7 @@ func IsEmpty(value interface{}, traceSource ...bool) bool { reflect.Array: return rv.Len() == 0 - case reflect.Ptr: + case reflect.Pointer: if len(traceSource) > 0 && traceSource[0] { return IsEmpty(rv.Elem()) } @@ -198,11 +198,11 @@ func IsEmpty(value interface{}, traceSource ...bool) bool { } } -// IsNil checks whether given `value` is nil, especially for interface{} type value. +// IsNil checks whether given `value` is nil, especially for any type value. // Parameter `traceSource` is used for tracing to the source variable if given `value` is type of pointer // that also points to a pointer. It returns nil if the source is nil when `traceSource` is true. // Note that it might use reflect feature which affects performance a little. -func IsNil(value interface{}, traceSource ...bool) bool { +func IsNil(value any, traceSource ...bool) bool { if value == nil { return true } @@ -221,15 +221,15 @@ func IsNil(value interface{}, traceSource ...bool) bool { reflect.UnsafePointer: return !rv.IsValid() || rv.IsNil() - case reflect.Ptr: + case reflect.Pointer: if len(traceSource) > 0 && traceSource[0] { - for rv.Kind() == reflect.Ptr { + for rv.Kind() == reflect.Pointer { rv = rv.Elem() } if !rv.IsValid() { return true } - if rv.Kind() == reflect.Ptr { + if rv.Kind() == reflect.Pointer { return rv.IsNil() } } else { diff --git a/internal/fileinfo/fileinfo.go b/internal/fileinfo/fileinfo.go index d469e3ca792..717c85f1c7e 100644 --- a/internal/fileinfo/fileinfo.go +++ b/internal/fileinfo/fileinfo.go @@ -48,6 +48,6 @@ func (i *Info) ModTime() time.Time { return i.modTime } -func (i *Info) Sys() interface{} { +func (i *Info) Sys() any { return nil } diff --git a/internal/httputil/httputils.go b/internal/httputil/httputils.go index 55f181ed8ec..41603e042c0 100644 --- a/internal/httputil/httputils.go +++ b/internal/httputil/httputils.go @@ -25,12 +25,12 @@ const ( // string/[]byte/map/struct/*struct. // // The optional parameter `noUrlEncode` specifies whether ignore the url encoding for the data. -func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) { +func BuildParams(params any, noUrlEncode ...bool) (encodedParamStr string) { // If given string/[]byte, converts and returns it directly as string. switch v := params.(type) { case string, []byte: return gconv.String(params) - case []interface{}: + case []any: if len(v) > 0 { params = v[0] } else { @@ -79,8 +79,8 @@ func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr strin } // HeaderToMap coverts request headers to map. -func HeaderToMap(header http.Header) map[string]interface{} { - m := make(map[string]interface{}) +func HeaderToMap(header http.Header) map[string]any { + m := make(map[string]any) for k, v := range header { if len(v) > 1 { m[k] = v diff --git a/internal/instance/instance.go b/internal/instance/instance.go index a5c021505e7..6af0fa2d2e7 100644 --- a/internal/instance/instance.go +++ b/internal/instance/instance.go @@ -33,25 +33,25 @@ func getGroup(key string) *gmap.StrAnyMap { } // Get returns the instance by given name. -func Get(name string) interface{} { +func Get(name string) any { return getGroup(name).Get(name) } // Set sets an instance to the instance manager with given name. -func Set(name string, instance interface{}) { +func Set(name string, instance any) { getGroup(name).Set(name, instance) } // GetOrSet returns the instance by name, // or set instance to the instance manager if it does not exist and returns this instance. -func GetOrSet(name string, instance interface{}) interface{} { +func GetOrSet(name string, instance any) any { return getGroup(name).GetOrSet(name, instance) } // GetOrSetFunc returns the instance by name, // or sets instance with returned value of callback function `f` if it does not exist // and then returns this instance. -func GetOrSetFunc(name string, f func() interface{}) interface{} { +func GetOrSetFunc(name string, f func() any) any { return getGroup(name).GetOrSetFunc(name, f) } @@ -61,13 +61,13 @@ func GetOrSetFunc(name string, f func() interface{}) interface{} { // // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f` // with mutex.Lock of the hash map. -func GetOrSetFuncLock(name string, f func() interface{}) interface{} { +func GetOrSetFuncLock(name string, f func() any) any { return getGroup(name).GetOrSetFuncLock(name, f) } // SetIfNotExist sets `instance` to the map if the `name` does not exist, then returns true. // It returns false if `name` exists, and `instance` would be ignored. -func SetIfNotExist(name string, instance interface{}) bool { +func SetIfNotExist(name string, instance any) bool { return getGroup(name).SetIfNotExist(name, instance) } diff --git a/internal/instance/instance_test.go b/internal/instance/instance_test.go index afdda594a6a..c29cb92118f 100644 --- a/internal/instance/instance_test.go +++ b/internal/instance/instance_test.go @@ -24,13 +24,13 @@ func Test_SetGet(t *testing.T) { t.Assert(instance.Get("test-1"), 1) }) gtest.C(t, func(t *gtest.T) { - t.Assert(instance.GetOrSetFunc("test-2", func() interface{} { + t.Assert(instance.GetOrSetFunc("test-2", func() any { return 2 }), 2) t.Assert(instance.Get("test-2"), 2) }) gtest.C(t, func(t *gtest.T) { - t.Assert(instance.GetOrSetFuncLock("test-3", func() interface{} { + t.Assert(instance.GetOrSetFuncLock("test-3", func() any { return 3 }), 3) t.Assert(instance.Get("test-3"), 3) diff --git a/internal/intlog/intlog.go b/internal/intlog/intlog.go index 57541f06542..1bc118b2862 100644 --- a/internal/intlog/intlog.go +++ b/internal/intlog/intlog.go @@ -26,7 +26,7 @@ const ( // Print prints `v` with newline using fmt.Println. // The parameter `v` can be multiple variables. -func Print(ctx context.Context, v ...interface{}) { +func Print(ctx context.Context, v ...any) { if !utils.IsDebugEnabled() { return } @@ -35,7 +35,7 @@ func Print(ctx context.Context, v ...interface{}) { // Printf prints `v` with format `format` using fmt.Printf. // The parameter `v` can be multiple variables. -func Printf(ctx context.Context, format string, v ...interface{}) { +func Printf(ctx context.Context, format string, v ...any) { if !utils.IsDebugEnabled() { return } @@ -44,7 +44,7 @@ func Printf(ctx context.Context, format string, v ...interface{}) { // Error prints `v` with newline using fmt.Println. // The parameter `v` can be multiple variables. -func Error(ctx context.Context, v ...interface{}) { +func Error(ctx context.Context, v ...any) { if !utils.IsDebugEnabled() { return } @@ -52,7 +52,7 @@ func Error(ctx context.Context, v ...interface{}) { } // Errorf prints `v` with format `format` using fmt.Printf. -func Errorf(ctx context.Context, format string, v ...interface{}) { +func Errorf(ctx context.Context, format string, v ...any) { if !utils.IsDebugEnabled() { return } diff --git a/internal/json/json.go b/internal/json/json.go index 374aec688ee..88c70507c96 100644 --- a/internal/json/json.go +++ b/internal/json/json.go @@ -24,7 +24,7 @@ type RawMessage = json.RawMessage // // Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API // Refer to https://godoc.org/encoding/json#Marshal for more information. -func Marshal(v interface{}) (marshaledBytes []byte, err error) { +func Marshal(v any) (marshaledBytes []byte, err error) { marshaledBytes, err = json.Marshal(v) if err != nil { err = gerror.Wrap(err, `json.Marshal failed`) @@ -33,7 +33,7 @@ func Marshal(v interface{}) (marshaledBytes []byte, err error) { } // MarshalIndent same as json.MarshalIndent. -func MarshalIndent(v interface{}, prefix, indent string) (marshaledBytes []byte, err error) { +func MarshalIndent(v any, prefix, indent string) (marshaledBytes []byte, err error) { marshaledBytes, err = json.MarshalIndent(v, prefix, indent) if err != nil { err = gerror.Wrap(err, `json.MarshalIndent failed`) @@ -45,7 +45,7 @@ func MarshalIndent(v interface{}, prefix, indent string) (marshaledBytes []byte, // // Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. // Refer to https://godoc.org/encoding/json#Unmarshal for more information. -func Unmarshal(data []byte, v interface{}) (err error) { +func Unmarshal(data []byte, v any) (err error) { err = json.Unmarshal(data, v) if err != nil { err = gerror.Wrap(err, `json.Unmarshal failed`) @@ -54,7 +54,7 @@ func Unmarshal(data []byte, v interface{}) (err error) { } // UnmarshalUseNumber decodes the json data bytes to target interface using number option. -func UnmarshalUseNumber(data []byte, v interface{}) (err error) { +func UnmarshalUseNumber(data []byte, v any) (err error) { decoder := NewDecoder(bytes.NewReader(data)) decoder.UseNumber() err = decoder.Decode(v) diff --git a/internal/reflection/reflection.go b/internal/reflection/reflection.go index 30a4cdedc9e..0fccd35050d 100644 --- a/internal/reflection/reflection.go +++ b/internal/reflection/reflection.go @@ -19,7 +19,7 @@ type OriginValueAndKindOutput struct { } // OriginValueAndKind retrieves and returns the original reflect value and kind. -func OriginValueAndKind(value interface{}) (out OriginValueAndKindOutput) { +func OriginValueAndKind(value any) (out OriginValueAndKindOutput) { if v, ok := value.(reflect.Value); ok { out.InputValue = v } else { @@ -28,7 +28,7 @@ func OriginValueAndKind(value interface{}) (out OriginValueAndKindOutput) { out.InputKind = out.InputValue.Kind() out.OriginValue = out.InputValue out.OriginKind = out.InputKind - for out.OriginKind == reflect.Ptr { + for out.OriginKind == reflect.Pointer { out.OriginValue = out.OriginValue.Elem() out.OriginKind = out.OriginValue.Kind() } @@ -43,7 +43,7 @@ type OriginTypeAndKindOutput struct { } // OriginTypeAndKind retrieves and returns the original reflect type and kind. -func OriginTypeAndKind(value interface{}) (out OriginTypeAndKindOutput) { +func OriginTypeAndKind(value any) (out OriginTypeAndKindOutput) { if value == nil { return } @@ -59,7 +59,7 @@ func OriginTypeAndKind(value interface{}) (out OriginTypeAndKindOutput) { out.InputKind = out.InputType.Kind() out.OriginType = out.InputType out.OriginKind = out.InputKind - for out.OriginKind == reflect.Ptr { + for out.OriginKind == reflect.Pointer { out.OriginType = out.OriginType.Elem() out.OriginKind = out.OriginType.Kind() } @@ -67,7 +67,7 @@ func OriginTypeAndKind(value interface{}) (out OriginTypeAndKindOutput) { } // ValueToInterface converts reflect value to its interface type. -func ValueToInterface(v reflect.Value) (value interface{}, ok bool) { +func ValueToInterface(v reflect.Value) (value any, ok bool) { if v.IsValid() && v.CanInterface() { return v.Interface(), true } @@ -84,7 +84,7 @@ func ValueToInterface(v reflect.Value) (value interface{}, ok bool) { return v.Complex(), true case reflect.String: return v.String(), true - case reflect.Ptr: + case reflect.Pointer: return ValueToInterface(v.Elem()) case reflect.Interface: return ValueToInterface(v.Elem()) diff --git a/internal/reflection/reflection_test.go b/internal/reflection/reflection_test.go index 417cf807cf7..8385669a681 100644 --- a/internal/reflection/reflection_test.go +++ b/internal/reflection/reflection_test.go @@ -24,7 +24,7 @@ func Test_OriginValueAndKind(t *testing.T) { gtest.C(t, func(t *gtest.T) { var s = "s" out := reflection.OriginValueAndKind(&s) - t.Assert(out.InputKind, reflect.Ptr) + t.Assert(out.InputKind, reflect.Pointer) t.Assert(out.OriginKind, reflect.String) }) gtest.C(t, func(t *gtest.T) { @@ -36,7 +36,7 @@ func Test_OriginValueAndKind(t *testing.T) { gtest.C(t, func(t *gtest.T) { var s []int out := reflection.OriginValueAndKind(&s) - t.Assert(out.InputKind, reflect.Ptr) + t.Assert(out.InputKind, reflect.Pointer) t.Assert(out.OriginKind, reflect.Slice) }) } @@ -51,7 +51,7 @@ func Test_OriginTypeAndKind(t *testing.T) { gtest.C(t, func(t *gtest.T) { var s = "s" out := reflection.OriginTypeAndKind(&s) - t.Assert(out.InputKind, reflect.Ptr) + t.Assert(out.InputKind, reflect.Pointer) t.Assert(out.OriginKind, reflect.String) }) gtest.C(t, func(t *gtest.T) { @@ -63,7 +63,7 @@ func Test_OriginTypeAndKind(t *testing.T) { gtest.C(t, func(t *gtest.T) { var s []int out := reflection.OriginTypeAndKind(&s) - t.Assert(out.InputKind, reflect.Ptr) + t.Assert(out.InputKind, reflect.Pointer) t.Assert(out.OriginKind, reflect.Slice) }) } diff --git a/internal/utils/utils_array.go b/internal/utils/utils_array.go index b96e039e6fa..2b566e0979b 100644 --- a/internal/utils/utils_array.go +++ b/internal/utils/utils_array.go @@ -10,10 +10,10 @@ import "reflect" // IsArray checks whether given value is array/slice. // Note that it uses reflect internally implementing this feature. -func IsArray(value interface{}) bool { +func IsArray(value any) bool { rv := reflect.ValueOf(value) kind := rv.Kind() - if kind == reflect.Ptr { + if kind == reflect.Pointer { rv = rv.Elem() kind = rv.Kind() } diff --git a/internal/utils/utils_is.go b/internal/utils/utils_is.go index 01fe759ee7f..852acae2ec8 100644 --- a/internal/utils/utils_is.go +++ b/internal/utils/utils_is.go @@ -12,18 +12,18 @@ import ( "github.com/gogf/gf/v2/internal/empty" ) -// IsNil checks whether `value` is nil, especially for interface{} type value. -func IsNil(value interface{}) bool { +// IsNil checks whether `value` is nil, especially for any type value. +func IsNil(value any) bool { return empty.IsNil(value) } // IsEmpty checks whether `value` is empty. -func IsEmpty(value interface{}) bool { +func IsEmpty(value any) bool { return empty.IsEmpty(value) } // IsInt checks whether `value` is type of int. -func IsInt(value interface{}) bool { +func IsInt(value any) bool { switch value.(type) { case int, *int, int8, *int8, int16, *int16, int32, *int32, int64, *int64: return true @@ -32,7 +32,7 @@ func IsInt(value interface{}) bool { } // IsUint checks whether `value` is type of uint. -func IsUint(value interface{}) bool { +func IsUint(value any) bool { switch value.(type) { case uint, *uint, uint8, *uint8, uint16, *uint16, uint32, *uint32, uint64, *uint64: return true @@ -41,7 +41,7 @@ func IsUint(value interface{}) bool { } // IsFloat checks whether `value` is type of float. -func IsFloat(value interface{}) bool { +func IsFloat(value any) bool { switch value.(type) { case float32, *float32, float64, *float64: return true @@ -50,12 +50,12 @@ func IsFloat(value interface{}) bool { } // IsSlice checks whether `value` is type of slice. -func IsSlice(value interface{}) bool { +func IsSlice(value any) bool { var ( reflectValue = reflect.ValueOf(value) reflectKind = reflectValue.Kind() ) - for reflectKind == reflect.Ptr { + for reflectKind == reflect.Pointer { reflectValue = reflectValue.Elem() reflectKind = reflectValue.Kind() } @@ -67,12 +67,12 @@ func IsSlice(value interface{}) bool { } // IsMap checks whether `value` is type of map. -func IsMap(value interface{}) bool { +func IsMap(value any) bool { var ( reflectValue = reflect.ValueOf(value) reflectKind = reflectValue.Kind() ) - for reflectKind == reflect.Ptr { + for reflectKind == reflect.Pointer { reflectValue = reflectValue.Elem() reflectKind = reflectValue.Kind() } @@ -84,13 +84,13 @@ func IsMap(value interface{}) bool { } // IsStruct checks whether `value` is type of struct. -func IsStruct(value interface{}) bool { +func IsStruct(value any) bool { reflectType := reflect.TypeOf(value) if reflectType == nil { return false } reflectKind := reflectType.Kind() - for reflectKind == reflect.Ptr { + for reflectKind == reflect.Pointer { reflectType = reflectType.Elem() reflectKind = reflectType.Kind() } diff --git a/internal/utils/utils_list.go b/internal/utils/utils_list.go index 355ad9f8e7a..e78037561dc 100644 --- a/internal/utils/utils_list.go +++ b/internal/utils/utils_list.go @@ -8,13 +8,13 @@ package utils import "fmt" -// ListToMapByKey converts `list` to a map[string]interface{} of which key is specified by `key`. +// ListToMapByKey converts `list` to a map[string]any of which key is specified by `key`. // Note that the item value may be type of slice. -func ListToMapByKey(list []map[string]interface{}, key string) map[string]interface{} { +func ListToMapByKey(list []map[string]any, key string) map[string]any { var ( s = "" - m = make(map[string]interface{}) - tempMap = make(map[string][]interface{}) + m = make(map[string]any) + tempMap = make(map[string][]any) hasMultiValues bool ) for _, item := range list { diff --git a/internal/utils/utils_map.go b/internal/utils/utils_map.go index fba7da77c85..e000ef55937 100644 --- a/internal/utils/utils_map.go +++ b/internal/utils/utils_map.go @@ -9,7 +9,7 @@ package utils // MapPossibleItemByKey tries to find the possible key-value pair for given key ignoring cases and symbols. // // Note that this function might be of low performance. -func MapPossibleItemByKey(data map[string]interface{}, key string) (foundKey string, foundValue interface{}) { +func MapPossibleItemByKey(data map[string]any, key string) (foundKey string, foundValue any) { if len(data) == 0 { return } @@ -29,7 +29,7 @@ func MapPossibleItemByKey(data map[string]interface{}, key string) (foundKey str // It checks the key ignoring cases and symbols. // // Note that this function might be of low performance. -func MapContainsPossibleKey(data map[string]interface{}, key string) bool { +func MapContainsPossibleKey(data map[string]any, key string) bool { if k, _ := MapPossibleItemByKey(data, key); k != "" { return true } diff --git a/internal/utils/utils_reflect.go b/internal/utils/utils_reflect.go index c217e407b7b..7fc1a84136b 100644 --- a/internal/utils/utils_reflect.go +++ b/internal/utils/utils_reflect.go @@ -12,13 +12,13 @@ import ( // CanCallIsNil Can reflect.Value call reflect.Value.IsNil. // It can avoid reflect.Value.IsNil panics. -func CanCallIsNil(v interface{}) bool { +func CanCallIsNil(v any) bool { rv, ok := v.(reflect.Value) if !ok { return false } switch rv.Kind() { - case reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: + case reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.Slice, reflect.UnsafePointer: return true default: return false diff --git a/net/gclient/gclient_bytes.go b/net/gclient/gclient_bytes.go index 1899b920e63..a4cf2af1afd 100644 --- a/net/gclient/gclient_bytes.go +++ b/net/gclient/gclient_bytes.go @@ -14,53 +14,53 @@ import ( ) // GetBytes sends a GET request, retrieves and returns the result content as bytes. -func (c *Client) GetBytes(ctx context.Context, url string, data ...interface{}) []byte { +func (c *Client) GetBytes(ctx context.Context, url string, data ...any) []byte { return c.RequestBytes(ctx, http.MethodGet, url, data...) } // PutBytes sends a PUT request, retrieves and returns the result content as bytes. -func (c *Client) PutBytes(ctx context.Context, url string, data ...interface{}) []byte { +func (c *Client) PutBytes(ctx context.Context, url string, data ...any) []byte { return c.RequestBytes(ctx, http.MethodPut, url, data...) } // PostBytes sends a POST request, retrieves and returns the result content as bytes. -func (c *Client) PostBytes(ctx context.Context, url string, data ...interface{}) []byte { +func (c *Client) PostBytes(ctx context.Context, url string, data ...any) []byte { return c.RequestBytes(ctx, http.MethodPost, url, data...) } // DeleteBytes sends a DELETE request, retrieves and returns the result content as bytes. -func (c *Client) DeleteBytes(ctx context.Context, url string, data ...interface{}) []byte { +func (c *Client) DeleteBytes(ctx context.Context, url string, data ...any) []byte { return c.RequestBytes(ctx, http.MethodDelete, url, data...) } // HeadBytes sends a HEAD request, retrieves and returns the result content as bytes. -func (c *Client) HeadBytes(ctx context.Context, url string, data ...interface{}) []byte { +func (c *Client) HeadBytes(ctx context.Context, url string, data ...any) []byte { return c.RequestBytes(ctx, http.MethodHead, url, data...) } // PatchBytes sends a PATCH request, retrieves and returns the result content as bytes. -func (c *Client) PatchBytes(ctx context.Context, url string, data ...interface{}) []byte { +func (c *Client) PatchBytes(ctx context.Context, url string, data ...any) []byte { return c.RequestBytes(ctx, http.MethodPatch, url, data...) } // ConnectBytes sends a CONNECT request, retrieves and returns the result content as bytes. -func (c *Client) ConnectBytes(ctx context.Context, url string, data ...interface{}) []byte { +func (c *Client) ConnectBytes(ctx context.Context, url string, data ...any) []byte { return c.RequestBytes(ctx, http.MethodConnect, url, data...) } // OptionsBytes sends an OPTIONS request, retrieves and returns the result content as bytes. -func (c *Client) OptionsBytes(ctx context.Context, url string, data ...interface{}) []byte { +func (c *Client) OptionsBytes(ctx context.Context, url string, data ...any) []byte { return c.RequestBytes(ctx, http.MethodOptions, url, data...) } // TraceBytes sends a TRACE request, retrieves and returns the result content as bytes. -func (c *Client) TraceBytes(ctx context.Context, url string, data ...interface{}) []byte { +func (c *Client) TraceBytes(ctx context.Context, url string, data ...any) []byte { return c.RequestBytes(ctx, http.MethodTrace, url, data...) } // RequestBytes sends request using given HTTP method and data, retrieves returns the result // as bytes. It reads and closes the response object internally automatically. -func (c *Client) RequestBytes(ctx context.Context, method string, url string, data ...interface{}) []byte { +func (c *Client) RequestBytes(ctx context.Context, method string, url string, data ...any) []byte { response, err := c.DoRequest(ctx, method, url, data...) if err != nil { intlog.Errorf(ctx, `%+v`, err) diff --git a/net/gclient/gclient_content.go b/net/gclient/gclient_content.go index 1a39c97a5c2..133feef261b 100644 --- a/net/gclient/gclient_content.go +++ b/net/gclient/gclient_content.go @@ -13,60 +13,60 @@ import ( // GetContent is a convenience method for sending GET request, which retrieves and returns // the result content and automatically closes response object. -func (c *Client) GetContent(ctx context.Context, url string, data ...interface{}) string { +func (c *Client) GetContent(ctx context.Context, url string, data ...any) string { return string(c.RequestBytes(ctx, http.MethodGet, url, data...)) } // PutContent is a convenience method for sending PUT request, which retrieves and returns // the result content and automatically closes response object. -func (c *Client) PutContent(ctx context.Context, url string, data ...interface{}) string { +func (c *Client) PutContent(ctx context.Context, url string, data ...any) string { return string(c.RequestBytes(ctx, http.MethodPut, url, data...)) } // PostContent is a convenience method for sending POST request, which retrieves and returns // the result content and automatically closes response object. -func (c *Client) PostContent(ctx context.Context, url string, data ...interface{}) string { +func (c *Client) PostContent(ctx context.Context, url string, data ...any) string { return string(c.RequestBytes(ctx, http.MethodPost, url, data...)) } // DeleteContent is a convenience method for sending DELETE request, which retrieves and returns // the result content and automatically closes response object. -func (c *Client) DeleteContent(ctx context.Context, url string, data ...interface{}) string { +func (c *Client) DeleteContent(ctx context.Context, url string, data ...any) string { return string(c.RequestBytes(ctx, http.MethodDelete, url, data...)) } // HeadContent is a convenience method for sending HEAD request, which retrieves and returns // the result content and automatically closes response object. -func (c *Client) HeadContent(ctx context.Context, url string, data ...interface{}) string { +func (c *Client) HeadContent(ctx context.Context, url string, data ...any) string { return string(c.RequestBytes(ctx, http.MethodHead, url, data...)) } // PatchContent is a convenience method for sending PATCH request, which retrieves and returns // the result content and automatically closes response object. -func (c *Client) PatchContent(ctx context.Context, url string, data ...interface{}) string { +func (c *Client) PatchContent(ctx context.Context, url string, data ...any) string { return string(c.RequestBytes(ctx, http.MethodPatch, url, data...)) } // ConnectContent is a convenience method for sending CONNECT request, which retrieves and returns // the result content and automatically closes response object. -func (c *Client) ConnectContent(ctx context.Context, url string, data ...interface{}) string { +func (c *Client) ConnectContent(ctx context.Context, url string, data ...any) string { return string(c.RequestBytes(ctx, http.MethodConnect, url, data...)) } // OptionsContent is a convenience method for sending OPTIONS request, which retrieves and returns // the result content and automatically closes response object. -func (c *Client) OptionsContent(ctx context.Context, url string, data ...interface{}) string { +func (c *Client) OptionsContent(ctx context.Context, url string, data ...any) string { return string(c.RequestBytes(ctx, http.MethodOptions, url, data...)) } // TraceContent is a convenience method for sending TRACE request, which retrieves and returns // the result content and automatically closes response object. -func (c *Client) TraceContent(ctx context.Context, url string, data ...interface{}) string { +func (c *Client) TraceContent(ctx context.Context, url string, data ...any) string { return string(c.RequestBytes(ctx, http.MethodTrace, url, data...)) } // RequestContent is a convenience method for sending custom http method request, which // retrieves and returns the result content and automatically closes response object. -func (c *Client) RequestContent(ctx context.Context, method string, url string, data ...interface{}) string { +func (c *Client) RequestContent(ctx context.Context, method string, url string, data ...any) string { return string(c.RequestBytes(ctx, method, url, data...)) } diff --git a/net/gclient/gclient_discovery.go b/net/gclient/gclient_discovery.go index ff9a1df9d9f..d24ce3095d5 100644 --- a/net/gclient/gclient_discovery.go +++ b/net/gclient/gclient_discovery.go @@ -69,7 +69,7 @@ func internalMiddlewareDiscovery(c *Client, r *http.Request) (response *Response // Balancer. var ( selectorMapKey = service.GetPrefix() - selectorMapValue = clientSelectorMap.GetOrSetFuncLock(selectorMapKey, func() interface{} { + selectorMapValue = clientSelectorMap.GetOrSetFuncLock(selectorMapKey, func() any { intlog.Printf(ctx, `http client create selector for service "%s"`, selectorMapKey) selector := c.builder.Build() // Update selector nodes. diff --git a/net/gclient/gclient_request.go b/net/gclient/gclient_request.go index a4619f23ff2..be63859a08a 100644 --- a/net/gclient/gclient_request.go +++ b/net/gclient/gclient_request.go @@ -31,55 +31,55 @@ import ( // Get send GET request and returns the response object. // Note that the response object MUST be closed if it'll never be used. -func (c *Client) Get(ctx context.Context, url string, data ...interface{}) (*Response, error) { +func (c *Client) Get(ctx context.Context, url string, data ...any) (*Response, error) { return c.DoRequest(ctx, http.MethodGet, url, data...) } // Put send PUT request and returns the response object. // Note that the response object MUST be closed if it'll never be used. -func (c *Client) Put(ctx context.Context, url string, data ...interface{}) (*Response, error) { +func (c *Client) Put(ctx context.Context, url string, data ...any) (*Response, error) { return c.DoRequest(ctx, http.MethodPut, url, data...) } // Post sends request using HTTP method POST and returns the response object. // Note that the response object MUST be closed if it'll never be used. -func (c *Client) Post(ctx context.Context, url string, data ...interface{}) (*Response, error) { +func (c *Client) Post(ctx context.Context, url string, data ...any) (*Response, error) { return c.DoRequest(ctx, http.MethodPost, url, data...) } // Delete send DELETE request and returns the response object. // Note that the response object MUST be closed if it'll never be used. -func (c *Client) Delete(ctx context.Context, url string, data ...interface{}) (*Response, error) { +func (c *Client) Delete(ctx context.Context, url string, data ...any) (*Response, error) { return c.DoRequest(ctx, http.MethodDelete, url, data...) } // Head send HEAD request and returns the response object. // Note that the response object MUST be closed if it'll never be used. -func (c *Client) Head(ctx context.Context, url string, data ...interface{}) (*Response, error) { +func (c *Client) Head(ctx context.Context, url string, data ...any) (*Response, error) { return c.DoRequest(ctx, http.MethodHead, url, data...) } // Patch send PATCH request and returns the response object. // Note that the response object MUST be closed if it'll never be used. -func (c *Client) Patch(ctx context.Context, url string, data ...interface{}) (*Response, error) { +func (c *Client) Patch(ctx context.Context, url string, data ...any) (*Response, error) { return c.DoRequest(ctx, http.MethodPatch, url, data...) } // Connect send CONNECT request and returns the response object. // Note that the response object MUST be closed if it'll never be used. -func (c *Client) Connect(ctx context.Context, url string, data ...interface{}) (*Response, error) { +func (c *Client) Connect(ctx context.Context, url string, data ...any) (*Response, error) { return c.DoRequest(ctx, http.MethodConnect, url, data...) } // Options send OPTIONS request and returns the response object. // Note that the response object MUST be closed if it'll never be used. -func (c *Client) Options(ctx context.Context, url string, data ...interface{}) (*Response, error) { +func (c *Client) Options(ctx context.Context, url string, data ...any) (*Response, error) { return c.DoRequest(ctx, http.MethodOptions, url, data...) } // Trace send TRACE request and returns the response object. // Note that the response object MUST be closed if it'll never be used. -func (c *Client) Trace(ctx context.Context, url string, data ...interface{}) (*Response, error) { +func (c *Client) Trace(ctx context.Context, url string, data ...any) (*Response, error) { return c.DoRequest(ctx, http.MethodTrace, url, data...) } @@ -123,7 +123,7 @@ func (c *Client) PostForm(ctx context.Context, url string, data map[string]strin // content for JSON format, and for that it automatically sets the Content-Type as // "application/json". func (c *Client) DoRequest( - ctx context.Context, method, url string, data ...interface{}, + ctx context.Context, method, url string, data ...any, ) (resp *Response, err error) { var requestStartTime = gtime.Now() req, err := c.prepareRequest(ctx, method, url, data...) @@ -159,7 +159,7 @@ func (c *Client) DoRequest( } // prepareRequest verifies request parameters, builds and returns http request. -func (c *Client) prepareRequest(ctx context.Context, method, url string, data ...interface{}) (req *http.Request, err error) { +func (c *Client) prepareRequest(ctx context.Context, method, url string, data ...any) (req *http.Request, err error) { method = strings.ToUpper(method) if len(c.prefix) > 0 { url = c.prefix + gstr.Trim(url) diff --git a/net/gclient/gclient_request_obj.go b/net/gclient/gclient_request_obj.go index 852eaff67ca..9f6d006a72f 100644 --- a/net/gclient/gclient_request_obj.go +++ b/net/gclient/gclient_request_obj.go @@ -41,7 +41,7 @@ import ( // ) // // err := DoRequestObj(ctx, req, &res) -func (c *Client) DoRequestObj(ctx context.Context, req, res interface{}) error { +func (c *Client) DoRequestObj(ctx context.Context, req, res any) error { var ( method = gmeta.Get(req, gtag.Method).String() path = gmeta.Get(req, gtag.Path).String() @@ -86,7 +86,7 @@ func (c *Client) DoRequestObj(ctx context.Context, req, res interface{}) error { // Eg: // /order/{id} -> /order/1 // /user/{name} -> /order/john -func (c *Client) handlePathForObjRequest(path string, req interface{}) string { +func (c *Client) handlePathForObjRequest(path string, req any) string { if gstr.Contains(path, "{") { requestParamsMap := gconv.Map(req) if len(requestParamsMap) > 0 { diff --git a/net/gclient/gclient_tracer_tracing.go b/net/gclient/gclient_tracer_tracing.go index 566138bdbc5..e88d6a826b1 100644 --- a/net/gclient/gclient_tracer_tracing.go +++ b/net/gclient/gclient_tracer_tracing.go @@ -32,7 +32,7 @@ type clientTracerTracing struct { span trace.Span request *http.Request requestBody []byte - headers map[string]interface{} + headers map[string]any mtx sync.Mutex } @@ -46,7 +46,7 @@ func newClientTracerTracing( Context: ctx, span: span, request: request, - headers: make(map[string]interface{}), + headers: make(map[string]any), } reqBodyContent, _ := io.ReadAll(ct.request.Body) diff --git a/net/gclient/gclient_var.go b/net/gclient/gclient_var.go index bb0ba66fe68..ca1828b6c48 100644 --- a/net/gclient/gclient_var.go +++ b/net/gclient/gclient_var.go @@ -17,70 +17,70 @@ import ( // GetVar sends a GET request, retrieves and converts the result content to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) GetVar(ctx context.Context, url string, data ...interface{}) *gvar.Var { +func (c *Client) GetVar(ctx context.Context, url string, data ...any) *gvar.Var { return c.RequestVar(ctx, http.MethodGet, url, data...) } // PutVar sends a PUT request, retrieves and converts the result content to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) PutVar(ctx context.Context, url string, data ...interface{}) *gvar.Var { +func (c *Client) PutVar(ctx context.Context, url string, data ...any) *gvar.Var { return c.RequestVar(ctx, http.MethodPut, url, data...) } // PostVar sends a POST request, retrieves and converts the result content to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) PostVar(ctx context.Context, url string, data ...interface{}) *gvar.Var { +func (c *Client) PostVar(ctx context.Context, url string, data ...any) *gvar.Var { return c.RequestVar(ctx, http.MethodPost, url, data...) } // DeleteVar sends a DELETE request, retrieves and converts the result content to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) DeleteVar(ctx context.Context, url string, data ...interface{}) *gvar.Var { +func (c *Client) DeleteVar(ctx context.Context, url string, data ...any) *gvar.Var { return c.RequestVar(ctx, http.MethodDelete, url, data...) } // HeadVar sends a HEAD request, retrieves and converts the result content to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) HeadVar(ctx context.Context, url string, data ...interface{}) *gvar.Var { +func (c *Client) HeadVar(ctx context.Context, url string, data ...any) *gvar.Var { return c.RequestVar(ctx, http.MethodHead, url, data...) } // PatchVar sends a PATCH request, retrieves and converts the result content to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) PatchVar(ctx context.Context, url string, data ...interface{}) *gvar.Var { +func (c *Client) PatchVar(ctx context.Context, url string, data ...any) *gvar.Var { return c.RequestVar(ctx, http.MethodPatch, url, data...) } // ConnectVar sends a CONNECT request, retrieves and converts the result content to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) ConnectVar(ctx context.Context, url string, data ...interface{}) *gvar.Var { +func (c *Client) ConnectVar(ctx context.Context, url string, data ...any) *gvar.Var { return c.RequestVar(ctx, http.MethodConnect, url, data...) } // OptionsVar sends an OPTIONS request, retrieves and converts the result content to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) OptionsVar(ctx context.Context, url string, data ...interface{}) *gvar.Var { +func (c *Client) OptionsVar(ctx context.Context, url string, data ...any) *gvar.Var { return c.RequestVar(ctx, http.MethodOptions, url, data...) } // TraceVar sends a TRACE request, retrieves and converts the result content to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) TraceVar(ctx context.Context, url string, data ...interface{}) *gvar.Var { +func (c *Client) TraceVar(ctx context.Context, url string, data ...any) *gvar.Var { return c.RequestVar(ctx, http.MethodTrace, url, data...) } // RequestVar sends request using given HTTP method and data, retrieves converts the result to *gvar.Var. // The client reads and closes the response object internally automatically. // The result *gvar.Var can be conveniently converted to any type you want. -func (c *Client) RequestVar(ctx context.Context, method string, url string, data ...interface{}) *gvar.Var { +func (c *Client) RequestVar(ctx context.Context, method string, url string, data ...any) *gvar.Var { response, err := c.DoRequest(ctx, method, url, data...) if err != nil { intlog.Errorf(ctx, `%+v`, err) diff --git a/net/gclient/gclient_z_unit_issue_test.go b/net/gclient/gclient_z_unit_issue_test.go index e3203f3e1d3..b397f114ac3 100644 --- a/net/gclient/gclient_z_unit_issue_test.go +++ b/net/gclient/gclient_z_unit_issue_test.go @@ -36,7 +36,7 @@ func Test_Issue3748(t *testing.T) { gtest.C(t, func(t *gtest.T) { client := gclient.New() client.SetHeader("Content-Type", "application/json") - data := map[string]interface{}{ + data := map[string]any{ "name": "@file:", "value": "json", } @@ -48,7 +48,7 @@ func Test_Issue3748(t *testing.T) { gtest.C(t, func(t *gtest.T) { client := gclient.New() client.SetHeader("Content-Type", "application/xml") - data := map[string]interface{}{ + data := map[string]any{ "name": "@file:", "value": "xml", } @@ -60,7 +60,7 @@ func Test_Issue3748(t *testing.T) { gtest.C(t, func(t *gtest.T) { client := gclient.New() client.SetHeader("Content-Type", "application/x-www-form-urlencoded") - data := map[string]interface{}{ + data := map[string]any{ "name": "@file:", "value": "x-www-form-urlencoded", } diff --git a/net/ghttp/ghttp.go b/net/ghttp/ghttp.go index dd5e0290682..60ecf1dce0e 100644 --- a/net/ghttp/ghttp.go +++ b/net/ghttp/ghttp.go @@ -38,7 +38,7 @@ type ( servers []*graceful.Server // Underlying http.Server array. serverCount *gtype.Int // Underlying http.Server number for internal usage. closeChan chan struct{} // Used for underlying server closing event notification. - serveTree map[string]interface{} // The route maps tree. + serveTree map[string]any // The route maps tree. serveCache *gcache.Cache // Server caches for internal usage. routesMap map[string][]*HandlerItem // Route map mainly for route dumps and repeated route checks. statusHandlerMap map[string][]HandlerFunc // Custom status handler map. diff --git a/net/ghttp/ghttp_func.go b/net/ghttp/ghttp_func.go index cf045c6b2a4..53df10e363c 100644 --- a/net/ghttp/ghttp_func.go +++ b/net/ghttp/ghttp_func.go @@ -22,7 +22,7 @@ func SupportedMethods() []string { // string/[]byte/map/struct/*struct. // // The optional parameter `noUrlEncode` specifies whether to ignore the url encoding for the data. -func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) { +func BuildParams(params any, noUrlEncode ...bool) (encodedParamStr string) { return httputil.BuildParams(params, noUrlEncode...) } diff --git a/net/ghttp/ghttp_middleware_handler_response.go b/net/ghttp/ghttp_middleware_handler_response.go index 23d3bab7ae8..87ffb9dc5bf 100644 --- a/net/ghttp/ghttp_middleware_handler_response.go +++ b/net/ghttp/ghttp_middleware_handler_response.go @@ -16,9 +16,9 @@ import ( // DefaultHandlerResponse is the default implementation of HandlerResponse. type DefaultHandlerResponse struct { - Code int `json:"code" dc:"Error code"` - Message string `json:"message" dc:"Error message"` - Data interface{} `json:"data" dc:"Result data for certain request according API definition"` + Code int `json:"code" dc:"Error code"` + Message string `json:"message" dc:"Error message"` + Data any `json:"data" dc:"Result data for certain request according API definition"` } const ( diff --git a/net/ghttp/ghttp_request.go b/net/ghttp/ghttp_request.go index 6bb4f622df2..220cbdd393f 100644 --- a/net/ghttp/ghttp_request.go +++ b/net/ghttp/ghttp_request.go @@ -39,28 +39,28 @@ type Request struct { // Private attributes for internal usage purpose. // ================================================================================================================= - handlers []*HandlerItemParsed // All matched handlers containing handler, hook and middleware for this request. - serveHandler *HandlerItemParsed // Real business handler serving for this request, not hook or middleware handler. - handlerResponse interface{} // Handler response object for Request/Response handler. - hasHookHandler bool // A bool marking whether there's hook handler in the handlers for performance purpose. - hasServeHandler bool // A bool marking whether there's serving handler in the handlers for performance purpose. - parsedQuery bool // A bool marking whether the GET parameters parsed. - parsedBody bool // A bool marking whether the request body parsed. - parsedForm bool // A bool marking whether request Form parsed for HTTP method PUT, POST, PATCH. - paramsMap map[string]interface{} // Custom parameters map. - routerMap map[string]string // Router parameters map, which might be nil if there are no router parameters. - queryMap map[string]interface{} // Query parameters map, which is nil if there's no query string. - formMap map[string]interface{} // Form parameters map, which is nil if there's no form of data from the client. - bodyMap map[string]interface{} // Body parameters map, which might be nil if their nobody content. - error error // Current executing error of the request. - exitAll bool // A bool marking whether current request is exited. - parsedHost string // The parsed host name for current host used by GetHost function. - clientIp string // The parsed client ip for current host used by GetClientIp function. - bodyContent []byte // Request body content. - isFileRequest bool // A bool marking whether current request is file serving. - viewObject *gview.View // Custom template view engine object for this response. - viewParams gview.Params // Custom template view variables for this response. - originUrlPath string // Original URL path that passed from client. + handlers []*HandlerItemParsed // All matched handlers containing handler, hook and middleware for this request. + serveHandler *HandlerItemParsed // Real business handler serving for this request, not hook or middleware handler. + handlerResponse any // Handler response object for Request/Response handler. + hasHookHandler bool // A bool marking whether there's hook handler in the handlers for performance purpose. + hasServeHandler bool // A bool marking whether there's serving handler in the handlers for performance purpose. + parsedQuery bool // A bool marking whether the GET parameters parsed. + parsedBody bool // A bool marking whether the request body parsed. + parsedForm bool // A bool marking whether request Form parsed for HTTP method PUT, POST, PATCH. + paramsMap map[string]any // Custom parameters map. + routerMap map[string]string // Router parameters map, which might be nil if there are no router parameters. + queryMap map[string]any // Query parameters map, which is nil if there's no query string. + formMap map[string]any // Form parameters map, which is nil if there's no form of data from the client. + bodyMap map[string]any // Body parameters map, which might be nil if their nobody content. + error error // Current executing error of the request. + exitAll bool // A bool marking whether current request is exited. + parsedHost string // The parsed host name for current host used by GetHost function. + clientIp string // The parsed client ip for current host used by GetClientIp function. + bodyContent []byte // Request body content. + isFileRequest bool // A bool marking whether current request is file serving. + viewObject *gview.View // Custom template view engine object for this response. + viewParams gview.Params // Custom template view variables for this response. + originUrlPath string // Original URL path that passed from client. } // staticFile is the file struct for static file service. diff --git a/net/ghttp/ghttp_request_param.go b/net/ghttp/ghttp_request_param.go index e22113ee8a0..4ff6475df30 100644 --- a/net/ghttp/ghttp_request_param.go +++ b/net/ghttp/ghttp_request_param.go @@ -51,27 +51,27 @@ var ( // 2. Multiple struct, post content like: [{"id":1, "name":"john"}, {"id":, "name":"smith"}] // // TODO: Improve the performance by reducing duplicated reflect usage on the same variable across packages. -func (r *Request) Parse(pointer interface{}) error { +func (r *Request) Parse(pointer any) error { return r.doParse(pointer, parseTypeRequest) } // ParseQuery performs like function Parse, but only parses the query parameters. -func (r *Request) ParseQuery(pointer interface{}) error { +func (r *Request) ParseQuery(pointer any) error { return r.doParse(pointer, parseTypeQuery) } // ParseForm performs like function Parse, but only parses the form parameters or the body content. -func (r *Request) ParseForm(pointer interface{}) error { +func (r *Request) ParseForm(pointer any) error { return r.doParse(pointer, parseTypeForm) } // doParse parses the request data to struct/structs according to request type. -func (r *Request) doParse(pointer interface{}, requestType int) error { +func (r *Request) doParse(pointer any, requestType int) error { var ( reflectVal1 = reflect.ValueOf(pointer) reflectKind1 = reflectVal1.Kind() ) - if reflectKind1 != reflect.Ptr { + if reflectKind1 != reflect.Pointer { return gerror.NewCodef( gcode.CodeInvalidParameter, `invalid parameter type "%v", of which kind should be of *struct/**struct/*[]struct/*[]*struct, but got: "%v"`, @@ -87,10 +87,10 @@ func (r *Request) doParse(pointer interface{}, requestType int) error { // Single struct, post content like: // 1. {"id":1, "name":"john"} // 2. ?id=1&name=john - case reflect.Ptr, reflect.Struct: + case reflect.Pointer, reflect.Struct: var ( err error - data map[string]interface{} + data map[string]any ) // Converting. switch requestType { @@ -144,7 +144,7 @@ func (r *Request) doParse(pointer interface{}, requestType int) error { // Get is alias of GetRequest, which is one of the most commonly used functions for // retrieving parameter. // See r.GetRequest. -func (r *Request) Get(key string, def ...interface{}) *gvar.Var { +func (r *Request) Get(key string, def ...any) *gvar.Var { return r.GetRequest(key, def...) } @@ -191,19 +191,19 @@ func (r *Request) GetJson() (*gjson.Json, error) { // GetMap is an alias and convenient function for GetRequestMap. // See GetRequestMap. -func (r *Request) GetMap(def ...map[string]interface{}) map[string]interface{} { +func (r *Request) GetMap(def ...map[string]any) map[string]any { return r.GetRequestMap(def...) } // GetMapStrStr is an alias and convenient function for GetRequestMapStrStr. // See GetRequestMapStrStr. -func (r *Request) GetMapStrStr(def ...map[string]interface{}) map[string]string { +func (r *Request) GetMapStrStr(def ...map[string]any) map[string]string { return r.GetRequestMapStrStr(def...) } // GetStruct is an alias and convenient function for GetRequestStruct. // See GetRequestStruct. -func (r *Request) GetStruct(pointer interface{}, mapping ...map[string]string) error { +func (r *Request) GetStruct(pointer any, mapping ...map[string]string) error { return r.GetRequestStruct(pointer, mapping...) } diff --git a/net/ghttp/ghttp_request_param_ctx.go b/net/ghttp/ghttp_request_param_ctx.go index ab127e954da..1fea4160f7f 100644 --- a/net/ghttp/ghttp_request_param_ctx.go +++ b/net/ghttp/ghttp_request_param_ctx.go @@ -60,7 +60,7 @@ func (r *Request) SetCtx(ctx context.Context) { // GetCtxVar retrieves and returns a Var with a given key name. // The optional parameter `def` specifies the default value of the Var if given `key` // does not exist in the context. -func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var { +func (r *Request) GetCtxVar(key any, def ...any) *gvar.Var { value := r.Context().Value(key) if value == nil && len(def) > 0 { value = def[0] @@ -69,7 +69,7 @@ func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var { } // SetCtxVar sets custom parameter to context with key-value pairs. -func (r *Request) SetCtxVar(key interface{}, value interface{}) { +func (r *Request) SetCtxVar(key any, value any) { var ctx = r.Context() ctx = context.WithValue(ctx, key, value) *r.Request = *r.WithContext(ctx) diff --git a/net/ghttp/ghttp_request_param_form.go b/net/ghttp/ghttp_request_param_form.go index 49a36cf9616..68deb0a6736 100644 --- a/net/ghttp/ghttp_request_param_form.go +++ b/net/ghttp/ghttp_request_param_form.go @@ -12,17 +12,17 @@ import ( ) // SetForm sets custom form value with key-value pairs. -func (r *Request) SetForm(key string, value interface{}) { +func (r *Request) SetForm(key string, value any) { r.parseForm() if r.formMap == nil { - r.formMap = make(map[string]interface{}) + r.formMap = make(map[string]any) } r.formMap[key] = value } // GetForm retrieves and returns parameter `key` from form. // It returns `def` if `key` does not exist in the form and `def` is given, or else it returns nil. -func (r *Request) GetForm(key string, def ...interface{}) *gvar.Var { +func (r *Request) GetForm(key string, def ...any) *gvar.Var { r.parseForm() if len(r.formMap) > 0 { if value, ok := r.formMap[key]; ok { @@ -38,13 +38,13 @@ func (r *Request) GetForm(key string, def ...interface{}) *gvar.Var { // GetFormMap retrieves and returns all form parameters passed from client as map. // The parameter `kvMap` specifies the keys retrieving from client parameters, // the associated values are the default values if the client does not pass. -func (r *Request) GetFormMap(kvMap ...map[string]interface{}) map[string]interface{} { +func (r *Request) GetFormMap(kvMap ...map[string]any) map[string]any { r.parseForm() if len(kvMap) > 0 && kvMap[0] != nil { if len(r.formMap) == 0 { return kvMap[0] } - m := make(map[string]interface{}, len(kvMap[0])) + m := make(map[string]any, len(kvMap[0])) for k, defValue := range kvMap[0] { if postValue, ok := r.formMap[k]; ok { m[k] = postValue @@ -61,7 +61,7 @@ func (r *Request) GetFormMap(kvMap ...map[string]interface{}) map[string]interfa // GetFormMapStrStr retrieves and returns all form parameters passed from client as map[string]string. // The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values // are the default values if the client does not pass. -func (r *Request) GetFormMapStrStr(kvMap ...map[string]interface{}) map[string]string { +func (r *Request) GetFormMapStrStr(kvMap ...map[string]any) map[string]string { formMap := r.GetFormMap(kvMap...) if len(formMap) > 0 { m := make(map[string]string, len(formMap)) @@ -76,7 +76,7 @@ func (r *Request) GetFormMapStrStr(kvMap ...map[string]interface{}) map[string]s // GetFormMapStrVar retrieves and returns all form parameters passed from client as map[string]*gvar.Var. // The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values // are the default values if the client does not pass. -func (r *Request) GetFormMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var { +func (r *Request) GetFormMapStrVar(kvMap ...map[string]any) map[string]*gvar.Var { formMap := r.GetFormMap(kvMap...) if len(formMap) > 0 { m := make(map[string]*gvar.Var, len(formMap)) @@ -91,16 +91,16 @@ func (r *Request) GetFormMapStrVar(kvMap ...map[string]interface{}) map[string]* // GetFormStruct retrieves all form parameters passed from client and converts them to // given struct object. Note that the parameter `pointer` is a pointer to the struct object. // The optional parameter `mapping` is used to specify the key to attribute mapping. -func (r *Request) GetFormStruct(pointer interface{}, mapping ...map[string]string) error { +func (r *Request) GetFormStruct(pointer any, mapping ...map[string]string) error { _, err := r.doGetFormStruct(pointer, mapping...) return err } -func (r *Request) doGetFormStruct(pointer interface{}, mapping ...map[string]string) (data map[string]interface{}, err error) { +func (r *Request) doGetFormStruct(pointer any, mapping ...map[string]string) (data map[string]any, err error) { r.parseForm() data = r.formMap if data == nil { - data = map[string]interface{}{} + data = map[string]any{} } if err = r.mergeDefaultStructValue(data, pointer); err != nil { return data, nil diff --git a/net/ghttp/ghttp_request_param_handler.go b/net/ghttp/ghttp_request_param_handler.go index 3863da8b5bc..9ac02b19076 100644 --- a/net/ghttp/ghttp_request_param_handler.go +++ b/net/ghttp/ghttp_request_param_handler.go @@ -7,7 +7,7 @@ package ghttp // GetHandlerResponse retrieves and returns the handler response object and its error. -func (r *Request) GetHandlerResponse() interface{} { +func (r *Request) GetHandlerResponse() any { return r.handlerResponse } diff --git a/net/ghttp/ghttp_request_param_param.go b/net/ghttp/ghttp_request_param_param.go index 48c1d742997..ebaba0ea38e 100644 --- a/net/ghttp/ghttp_request_param_param.go +++ b/net/ghttp/ghttp_request_param_param.go @@ -9,17 +9,17 @@ package ghttp import "github.com/gogf/gf/v2/container/gvar" // SetParam sets custom parameter with key-value pairs. -func (r *Request) SetParam(key string, value interface{}) { +func (r *Request) SetParam(key string, value any) { if r.paramsMap == nil { - r.paramsMap = make(map[string]interface{}) + r.paramsMap = make(map[string]any) } r.paramsMap[key] = value } // SetParamMap sets custom parameter with key-value pair maps. -func (r *Request) SetParamMap(data map[string]interface{}) { +func (r *Request) SetParamMap(data map[string]any) { if r.paramsMap == nil { - r.paramsMap = make(map[string]interface{}) + r.paramsMap = make(map[string]any) } for k, v := range data { r.paramsMap[k] = v @@ -29,7 +29,7 @@ func (r *Request) SetParamMap(data map[string]interface{}) { // GetParam returns custom parameter with a given name `key`. // It returns `def` if `key` does not exist. // It returns nil if `def` is not passed. -func (r *Request) GetParam(key string, def ...interface{}) *gvar.Var { +func (r *Request) GetParam(key string, def ...any) *gvar.Var { if len(r.paramsMap) > 0 { if value, ok := r.paramsMap[key]; ok { return gvar.New(value) diff --git a/net/ghttp/ghttp_request_param_query.go b/net/ghttp/ghttp_request_param_query.go index 5badddbfe4a..2ad5ca5f59f 100644 --- a/net/ghttp/ghttp_request_param_query.go +++ b/net/ghttp/ghttp_request_param_query.go @@ -14,10 +14,10 @@ import ( ) // SetQuery sets custom query value with key-value pairs. -func (r *Request) SetQuery(key string, value interface{}) { +func (r *Request) SetQuery(key string, value any) { r.parseQuery() if r.queryMap == nil { - r.queryMap = make(map[string]interface{}) + r.queryMap = make(map[string]any) } r.queryMap[key] = value } @@ -28,7 +28,7 @@ func (r *Request) SetQuery(key string, value interface{}) { // // Note that if there are multiple parameters with the same name, the parameters are retrieved // and overwrote in order of priority: query > body. -func (r *Request) GetQuery(key string, def ...interface{}) *gvar.Var { +func (r *Request) GetQuery(key string, def ...any) *gvar.Var { r.parseQuery() if len(r.queryMap) > 0 { if value, ok := r.queryMap[key]; ok { @@ -55,17 +55,17 @@ func (r *Request) GetQuery(key string, def ...interface{}) *gvar.Var { // // Note that if there are multiple parameters with the same name, the parameters are retrieved and overwrote // in order of priority: query > body. -func (r *Request) GetQueryMap(kvMap ...map[string]interface{}) map[string]interface{} { +func (r *Request) GetQueryMap(kvMap ...map[string]any) map[string]any { r.parseQuery() if r.Method == http.MethodGet { r.parseBody() } - var m map[string]interface{} + var m map[string]any if len(kvMap) > 0 && kvMap[0] != nil { if len(r.queryMap) == 0 && len(r.bodyMap) == 0 { return kvMap[0] } - m = make(map[string]interface{}, len(kvMap[0])) + m = make(map[string]any, len(kvMap[0])) if len(r.bodyMap) > 0 { for k, v := range kvMap[0] { if postValue, ok := r.bodyMap[k]; ok { @@ -85,7 +85,7 @@ func (r *Request) GetQueryMap(kvMap ...map[string]interface{}) map[string]interf } } } else { - m = make(map[string]interface{}, len(r.queryMap)+len(r.bodyMap)) + m = make(map[string]any, len(r.queryMap)+len(r.bodyMap)) for k, v := range r.bodyMap { m[k] = v } @@ -102,7 +102,7 @@ func (r *Request) GetQueryMap(kvMap ...map[string]interface{}) map[string]interf // // retrieving from client parameters, the associated values are the default values if the client // does not pass. -func (r *Request) GetQueryMapStrStr(kvMap ...map[string]interface{}) map[string]string { +func (r *Request) GetQueryMapStrStr(kvMap ...map[string]any) map[string]string { queryMap := r.GetQueryMap(kvMap...) if len(queryMap) > 0 { m := make(map[string]string, len(queryMap)) @@ -118,7 +118,7 @@ func (r *Request) GetQueryMapStrStr(kvMap ...map[string]interface{}) map[string] // as map[string]*gvar.Var. The parameter `kvMap` specifies the keys // retrieving from client parameters, the associated values are the default values if the client // does not pass. -func (r *Request) GetQueryMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var { +func (r *Request) GetQueryMapStrVar(kvMap ...map[string]any) map[string]*gvar.Var { queryMap := r.GetQueryMap(kvMap...) if len(queryMap) > 0 { m := make(map[string]*gvar.Var, len(queryMap)) @@ -134,16 +134,16 @@ func (r *Request) GetQueryMapStrVar(kvMap ...map[string]interface{}) map[string] // and converts them to a given struct object. Note that the parameter `pointer` is a pointer // to the struct object. The optional parameter `mapping` is used to specify the key to // attribute mapping. -func (r *Request) GetQueryStruct(pointer interface{}, mapping ...map[string]string) error { +func (r *Request) GetQueryStruct(pointer any, mapping ...map[string]string) error { _, err := r.doGetQueryStruct(pointer, mapping...) return err } -func (r *Request) doGetQueryStruct(pointer interface{}, mapping ...map[string]string) (data map[string]interface{}, err error) { +func (r *Request) doGetQueryStruct(pointer any, mapping ...map[string]string) (data map[string]any, err error) { r.parseQuery() data = r.GetQueryMap() if data == nil { - data = map[string]interface{}{} + data = map[string]any{} } if err = r.mergeDefaultStructValue(data, pointer); err != nil { return data, nil diff --git a/net/ghttp/ghttp_request_param_request.go b/net/ghttp/ghttp_request_param_request.go index 622590f0905..5c7ebd0b1b2 100644 --- a/net/ghttp/ghttp_request_param_request.go +++ b/net/ghttp/ghttp_request_param_request.go @@ -15,14 +15,14 @@ import ( ) // GetRequest retrieves and returns the parameter named `key` passed from the client and -// custom params as interface{}, no matter what HTTP method the client is using. The +// custom params as any, no matter what HTTP method the client is using. The // parameter `def` specifies the default value if the `key` does not exist. // // GetRequest is one of the most commonly used functions for retrieving parameters. // // Note that if there are multiple parameters with the same name, the parameters are // retrieved and overwrote in order of priority: router < query < body < form < custom. -func (r *Request) GetRequest(key string, def ...interface{}) *gvar.Var { +func (r *Request) GetRequest(key string, def ...any) *gvar.Var { value := r.GetParam(key) if value.IsNil() { value = r.GetForm(key) @@ -59,7 +59,7 @@ func (r *Request) GetRequest(key string, def ...interface{}) *gvar.Var { // // Note that if there are multiple parameters with the same name, the parameters are retrieved // and overwrote in order of priority: router < query < body < form < custom. -func (r *Request) GetRequestMap(kvMap ...map[string]interface{}) map[string]interface{} { +func (r *Request) GetRequestMap(kvMap ...map[string]any) map[string]any { r.parseQuery() r.parseForm() r.parseBody() @@ -69,7 +69,7 @@ func (r *Request) GetRequestMap(kvMap ...map[string]interface{}) map[string]inte if len(kvMap) > 0 && kvMap[0] != nil { filter = true } - m := make(map[string]interface{}) + m := make(map[string]any) for k, v := range r.routerMap { if filter { if _, ok = kvMap[0][k]; !ok { @@ -135,7 +135,7 @@ func (r *Request) GetRequestMap(kvMap ...map[string]interface{}) map[string]inte // params as map[string]string, no matter what HTTP method the client is using. The parameter // `kvMap` specifies the keys retrieving from client parameters, the associated values are the // default values if the client does not pass. -func (r *Request) GetRequestMapStrStr(kvMap ...map[string]interface{}) map[string]string { +func (r *Request) GetRequestMapStrStr(kvMap ...map[string]any) map[string]string { requestMap := r.GetRequestMap(kvMap...) if len(requestMap) > 0 { m := make(map[string]string, len(requestMap)) @@ -151,7 +151,7 @@ func (r *Request) GetRequestMapStrStr(kvMap ...map[string]interface{}) map[strin // params as map[string]*gvar.Var, no matter what HTTP method the client is using. The parameter // `kvMap` specifies the keys retrieving from client parameters, the associated values are the // default values if the client does not pass. -func (r *Request) GetRequestMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var { +func (r *Request) GetRequestMapStrVar(kvMap ...map[string]any) map[string]*gvar.Var { requestMap := r.GetRequestMap(kvMap...) if len(requestMap) > 0 { m := make(map[string]*gvar.Var, len(requestMap)) @@ -167,15 +167,15 @@ func (r *Request) GetRequestMapStrVar(kvMap ...map[string]interface{}) map[strin // what HTTP method the client is using, and converts them to give the struct object. Note that // the parameter `pointer` is a pointer to the struct object. // The optional parameter `mapping` is used to specify the key to attribute mapping. -func (r *Request) GetRequestStruct(pointer interface{}, mapping ...map[string]string) error { +func (r *Request) GetRequestStruct(pointer any, mapping ...map[string]string) error { _, err := r.doGetRequestStruct(pointer, mapping...) return err } -func (r *Request) doGetRequestStruct(pointer interface{}, mapping ...map[string]string) (data map[string]interface{}, err error) { +func (r *Request) doGetRequestStruct(pointer any, mapping ...map[string]string) (data map[string]any, err error) { data = r.GetRequestMap() if data == nil { - data = map[string]interface{}{} + data = map[string]any{} } // `in` Tag Struct values. @@ -192,7 +192,7 @@ func (r *Request) doGetRequestStruct(pointer interface{}, mapping ...map[string] } // mergeDefaultStructValue merges the request parameters with default values from struct tag definition. -func (r *Request) mergeDefaultStructValue(data map[string]interface{}, pointer interface{}) error { +func (r *Request) mergeDefaultStructValue(data map[string]any, pointer any) error { fields := r.serveHandler.Handler.Info.ReqStructFields if len(fields) > 0 { for _, field := range fields { @@ -218,14 +218,14 @@ func (r *Request) mergeDefaultStructValue(data map[string]interface{}, pointer i } // mergeInTagStructValue merges the request parameters with header or cookie values from struct `in` tag definition. -func (r *Request) mergeInTagStructValue(data map[string]interface{}) error { +func (r *Request) mergeInTagStructValue(data map[string]any) error { fields := r.serveHandler.Handler.Info.ReqStructFields if len(fields) > 0 { var ( foundKey string - foundValue interface{} - headerMap = make(map[string]interface{}) - cookieMap = make(map[string]interface{}) + foundValue any + headerMap = make(map[string]any) + cookieMap = make(map[string]any) ) for k, v := range r.Header { @@ -257,7 +257,7 @@ func (r *Request) mergeInTagStructValue(data map[string]interface{}) error { } // mergeTagValueWithFoundKey merges the request parameters when the key does not exist in the map or overwritten is true or the value is nil. -func mergeTagValueWithFoundKey(data map[string]interface{}, overwritten bool, findKey string, fieldName string, tagValue interface{}) { +func mergeTagValueWithFoundKey(data map[string]any, overwritten bool, findKey string, fieldName string, tagValue any) { if foundKey, foundValue := gutil.MapPossibleItemByKey(data, findKey); foundKey == "" { data[fieldName] = tagValue } else { diff --git a/net/ghttp/ghttp_request_param_router.go b/net/ghttp/ghttp_request_param_router.go index ee816ba10f1..57a951a2230 100644 --- a/net/ghttp/ghttp_request_param_router.go +++ b/net/ghttp/ghttp_request_param_router.go @@ -22,7 +22,7 @@ func (r *Request) GetRouterMap() map[string]string { // GetRouter retrieves and returns the router value with given key name `key`. // It returns `def` if `key` does not exist. -func (r *Request) GetRouter(key string, def ...interface{}) *gvar.Var { +func (r *Request) GetRouter(key string, def ...any) *gvar.Var { if r.routerMap != nil { if v, ok := r.routerMap[key]; ok { return gvar.New(v) diff --git a/net/ghttp/ghttp_request_view.go b/net/ghttp/ghttp_request_view.go index 143ecc701bb..07c00f202a9 100644 --- a/net/ghttp/ghttp_request_view.go +++ b/net/ghttp/ghttp_request_view.go @@ -36,7 +36,7 @@ func (r *Request) Assigns(data gview.Params) { } // Assign binds a template variable to current request. -func (r *Request) Assign(key string, value interface{}) { +func (r *Request) Assign(key string, value any) { if r.viewParams == nil { r.viewParams = make(gview.Params) } diff --git a/net/ghttp/ghttp_response_view.go b/net/ghttp/ghttp_response_view.go index 06c0388f2f6..ff780f1235d 100644 --- a/net/ghttp/ghttp_response_view.go +++ b/net/ghttp/ghttp_response_view.go @@ -79,14 +79,14 @@ func (r *Response) ParseTplContent(content string, params ...gview.Params) (stri // buildInVars merges build-in variables into `params` and returns the new template variables. // TODO performance improving. -func (r *Response) buildInVars(params ...map[string]interface{}) map[string]interface{} { +func (r *Response) buildInVars(params ...map[string]any) map[string]any { m := gutil.MapMergeCopy(r.Request.viewParams) if len(params) > 0 { gutil.MapMerge(m, params[0]) } // Retrieve custom template variables from request object. sessionMap := gconv.MapDeep(r.Request.Session.MustData()) - gutil.MapMerge(m, map[string]interface{}{ + gutil.MapMerge(m, map[string]any{ "Form": r.Request.GetFormMap(), "Query": r.Request.GetQueryMap(), "Request": r.Request.GetMap(), diff --git a/net/ghttp/ghttp_response_write.go b/net/ghttp/ghttp_response_write.go index b5c41db62fd..352bcf8152a 100644 --- a/net/ghttp/ghttp_response_write.go +++ b/net/ghttp/ghttp_response_write.go @@ -18,7 +18,7 @@ import ( ) // Write writes `content` to the response buffer. -func (r *Response) Write(content ...interface{}) { +func (r *Response) Write(content ...any) { if r.IsHijacked() || len(content) == 0 { return } @@ -40,13 +40,13 @@ func (r *Response) Write(content ...interface{}) { // WriteExit writes `content` to the response buffer and exits executing of current handler. // The "Exit" feature is commonly used to replace usage of return statements in the handler, // for convenience. -func (r *Response) WriteExit(content ...interface{}) { +func (r *Response) WriteExit(content ...any) { r.Write(content...) r.Request.Exit() } // WriteOver overwrites the response buffer with `content`. -func (r *Response) WriteOver(content ...interface{}) { +func (r *Response) WriteOver(content ...any) { r.ClearBuffer() r.Write(content...) } @@ -54,26 +54,26 @@ func (r *Response) WriteOver(content ...interface{}) { // WriteOverExit overwrites the response buffer with `content` and exits executing // of current handler. The "Exit" feature is commonly used to replace usage of return // statements in the handler, for convenience. -func (r *Response) WriteOverExit(content ...interface{}) { +func (r *Response) WriteOverExit(content ...any) { r.WriteOver(content...) r.Request.Exit() } // Writef writes the response with fmt.Sprintf. -func (r *Response) Writef(format string, params ...interface{}) { +func (r *Response) Writef(format string, params ...any) { r.Write(fmt.Sprintf(format, params...)) } // WritefExit writes the response with fmt.Sprintf and exits executing of current handler. // The "Exit" feature is commonly used to replace usage of return statements in the handler, // for convenience. -func (r *Response) WritefExit(format string, params ...interface{}) { +func (r *Response) WritefExit(format string, params ...any) { r.Writef(format, params...) r.Request.Exit() } // Writeln writes the response with `content` and new line. -func (r *Response) Writeln(content ...interface{}) { +func (r *Response) Writeln(content ...any) { if len(content) == 0 { r.Write("\n") return @@ -84,26 +84,26 @@ func (r *Response) Writeln(content ...interface{}) { // WritelnExit writes the response with `content` and new line and exits executing // of current handler. The "Exit" feature is commonly used to replace usage of return // statements in the handler, for convenience. -func (r *Response) WritelnExit(content ...interface{}) { +func (r *Response) WritelnExit(content ...any) { r.Writeln(content...) r.Request.Exit() } // Writefln writes the response with fmt.Sprintf and new line. -func (r *Response) Writefln(format string, params ...interface{}) { +func (r *Response) Writefln(format string, params ...any) { r.Writeln(fmt.Sprintf(format, params...)) } // WriteflnExit writes the response with fmt.Sprintf and new line and exits executing // of current handler. The "Exit" feature is commonly used to replace usage of return // statement in the handler, for convenience. -func (r *Response) WriteflnExit(format string, params ...interface{}) { +func (r *Response) WriteflnExit(format string, params ...any) { r.Writefln(format, params...) r.Request.Exit() } // WriteJson writes `content` to the response with JSON format. -func (r *Response) WriteJson(content interface{}) { +func (r *Response) WriteJson(content any) { r.Header().Set("Content-Type", contentTypeJson) // If given string/[]byte, response it directly to the client. switch content.(type) { @@ -122,7 +122,7 @@ func (r *Response) WriteJson(content interface{}) { // WriteJsonExit writes `content` to the response with JSON format and exits executing // of current handler if success. The "Exit" feature is commonly used to replace usage of // return statements in the handler, for convenience. -func (r *Response) WriteJsonExit(content interface{}) { +func (r *Response) WriteJsonExit(content any) { r.WriteJson(content) r.Request.Exit() } @@ -130,7 +130,7 @@ func (r *Response) WriteJsonExit(content interface{}) { // WriteJsonP writes `content` to the response with JSONP format. // // Note that there should be a "callback" parameter in the request for JSONP format. -func (r *Response) WriteJsonP(content interface{}) { +func (r *Response) WriteJsonP(content any) { r.Header().Set("Content-Type", contentTypeJavascript) // If given string/[]byte, response it directly to client. switch content.(type) { @@ -160,13 +160,13 @@ func (r *Response) WriteJsonP(content interface{}) { // return statements in the handler, for convenience. // // Note that there should be a "callback" parameter in the request for JSONP format. -func (r *Response) WriteJsonPExit(content interface{}) { +func (r *Response) WriteJsonPExit(content any) { r.WriteJsonP(content) r.Request.Exit() } // WriteXml writes `content` to the response with XML format. -func (r *Response) WriteXml(content interface{}, rootTag ...string) { +func (r *Response) WriteXml(content any, rootTag ...string) { r.Header().Set("Content-Type", contentTypeXml) // If given string/[]byte, response it directly to clients. switch content.(type) { @@ -184,14 +184,14 @@ func (r *Response) WriteXml(content interface{}, rootTag ...string) { // WriteXmlExit writes `content` to the response with XML format and exits executing // of current handler if success. The "Exit" feature is commonly used to replace usage // of return statements in the handler, for convenience. -func (r *Response) WriteXmlExit(content interface{}, rootTag ...string) { +func (r *Response) WriteXmlExit(content any, rootTag ...string) { r.WriteXml(content, rootTag...) r.Request.Exit() } // WriteStatus writes HTTP `status` and `content` to the response. // Note that it does not set a Content-Type header here. -func (r *Response) WriteStatus(status int, content ...interface{}) { +func (r *Response) WriteStatus(status int, content ...any) { r.WriteHeader(status) if len(content) > 0 { r.Write(content...) @@ -203,7 +203,7 @@ func (r *Response) WriteStatus(status int, content ...interface{}) { // WriteStatusExit writes HTTP `status` and `content` to the response and exits executing // of current handler if success. The "Exit" feature is commonly used to replace usage of // return statements in the handler, for convenience. -func (r *Response) WriteStatusExit(status int, content ...interface{}) { +func (r *Response) WriteStatusExit(status int, content ...any) { r.WriteStatus(status, content...) r.Request.Exit() } diff --git a/net/ghttp/ghttp_server.go b/net/ghttp/ghttp_server.go index 6e84d9c952a..e636a02edc0 100644 --- a/net/ghttp/ghttp_server.go +++ b/net/ghttp/ghttp_server.go @@ -89,12 +89,12 @@ func serverProcessInit() { // GetServer creates and returns a server instance using given name and default configurations. // Note that the parameter `name` should be unique for different servers. It returns an existing // server instance if given `name` is already existing in the server mapping. -func GetServer(name ...interface{}) *Server { +func GetServer(name ...any) *Server { serverName := DefaultServerName if len(name) > 0 && name[0] != "" { serverName = gconv.String(name[0]) } - v := serverMapping.GetOrSetFuncLock(serverName, func() interface{} { + v := serverMapping.GetOrSetFuncLock(serverName, func() any { s := &Server{ instance: serverName, plugins: make([]Plugin, 0), @@ -102,7 +102,7 @@ func GetServer(name ...interface{}) *Server { closeChan: make(chan struct{}, 10000), serverCount: gtype.NewInt(), statusHandlerMap: make(map[string][]HandlerFunc), - serveTree: make(map[string]interface{}), + serveTree: make(map[string]any), serveCache: gcache.New(), routesMap: make(map[string][]*HandlerItem), openapi: goai.New(), @@ -407,7 +407,7 @@ func (s *Server) GetRoutes() []RouterItem { // The value of the map is a custom sorted array. if _, ok := m[item.Domain]; !ok { // Sort in ASC order. - m[item.Domain] = garray.NewSortedArray(func(v1, v2 interface{}) int { + m[item.Domain] = garray.NewSortedArray(func(v1, v2 any) int { item1 := v1.(RouterItem) item2 := v2.(RouterItem) r := 0 @@ -470,7 +470,7 @@ func Wait() { <-allShutdownChan // Remove plugins. - serverMapping.Iterator(func(k string, v interface{}) bool { + serverMapping.Iterator(func(k string, v any) bool { s := v.(*Server) if len(s.plugins) > 0 { for _, p := range s.plugins { diff --git a/net/ghttp/ghttp_server_admin.go b/net/ghttp/ghttp_server_admin.go index 987e51a3ea4..310841c283e 100644 --- a/net/ghttp/ghttp_server_admin.go +++ b/net/ghttp/ghttp_server_admin.go @@ -23,7 +23,7 @@ type utilAdmin struct{} // Index shows the administration page. func (p *utilAdmin) Index(r *Request) { - data := map[string]interface{}{ + data := map[string]any{ "pid": gproc.Pid(), "path": gfile.SelfPath(), "uri": strings.TrimRight(r.URL.Path, "/"), diff --git a/net/ghttp/ghttp_server_admin_process.go b/net/ghttp/ghttp_server_admin_process.go index 93dcecf1114..f7cf1554900 100644 --- a/net/ghttp/ghttp_server_admin_process.go +++ b/net/ghttp/ghttp_server_admin_process.go @@ -190,7 +190,7 @@ func forkRestartProcess(ctx context.Context, newExeFilePath ...string) error { // getServerFdMap returns all the servers name to file descriptor mapping as map. func getServerFdMap() map[string]listenerFdMap { sfm := make(map[string]listenerFdMap) - serverMapping.RLockFunc(func(m map[string]interface{}) { + serverMapping.RLockFunc(func(m map[string]any) { for k, v := range m { sfm[k] = v.(*Server).getListenerFdMap() } @@ -263,7 +263,7 @@ func shutdownWebServersGracefully(ctx context.Context, signal os.Signal) { } else { glog.Printf(ctx, "pid[%d]: server gracefully shutting down by api", gproc.Pid()) } - serverMapping.RLockFunc(func(m map[string]interface{}) { + serverMapping.RLockFunc(func(m map[string]any) { for _, v := range m { server := v.(*Server) server.doServiceDeregister() @@ -276,7 +276,7 @@ func shutdownWebServersGracefully(ctx context.Context, signal os.Signal) { // forceCloseWebServers forced shuts down all servers. func forceCloseWebServers(ctx context.Context) { - serverMapping.RLockFunc(func(m map[string]interface{}) { + serverMapping.RLockFunc(func(m map[string]any) { for _, v := range m { for _, s := range v.(*Server).servers { s.Close(ctx) diff --git a/net/ghttp/ghttp_server_config.go b/net/ghttp/ghttp_server_config.go index f5a6f4fe969..8ce6f4266ca 100644 --- a/net/ghttp/ghttp_server_config.go +++ b/net/ghttp/ghttp_server_config.go @@ -318,7 +318,7 @@ func NewConfig() ServerConfig { // ConfigFromMap creates and returns a ServerConfig object with given map and // default configuration object. -func ConfigFromMap(m map[string]interface{}) (ServerConfig, error) { +func ConfigFromMap(m map[string]any) (ServerConfig, error) { config := NewConfig() if err := gconv.Struct(m, &config); err != nil { return config, err @@ -327,7 +327,7 @@ func ConfigFromMap(m map[string]interface{}) (ServerConfig, error) { } // SetConfigWithMap sets the configuration for the server using map. -func (s *Server) SetConfigWithMap(m map[string]interface{}) error { +func (s *Server) SetConfigWithMap(m map[string]any) error { // The m now is a shallow copy of m. // Any changes to m does not affect the original one. // A little tricky, isn't it? diff --git a/net/ghttp/ghttp_server_config_static.go b/net/ghttp/ghttp_server_config_static.go index 651f6b6952c..2ea671f11a4 100644 --- a/net/ghttp/ghttp_server_config_static.go +++ b/net/ghttp/ghttp_server_config_static.go @@ -102,7 +102,7 @@ func (s *Server) AddStaticPath(prefix string, path string) { if len(s.config.StaticPaths) > 0 { s.config.StaticPaths = append(s.config.StaticPaths, addItem) // Sort the array by length of prefix from short to long. - array := garray.NewSortedArray(func(v1, v2 interface{}) int { + array := garray.NewSortedArray(func(v1, v2 any) int { s1 := gconv.String(v1) s2 := gconv.String(v2) r := len(s2) - len(s1) diff --git a/net/ghttp/ghttp_server_domain.go b/net/ghttp/ghttp_server_domain.go index 7d3dd4f7664..10a98d7805b 100644 --- a/net/ghttp/ghttp_server_domain.go +++ b/net/ghttp/ghttp_server_domain.go @@ -30,7 +30,7 @@ func (s *Server) Domain(domains string) *Domain { } // BindHandler binds the handler for the specified pattern. -func (d *Domain) BindHandler(pattern string, handler interface{}) { +func (d *Domain) BindHandler(pattern string, handler any) { for domain := range d.domains { d.server.BindHandler(pattern+"@"+domain, handler) } @@ -49,7 +49,7 @@ func (d *Domain) doBindHandler(ctx context.Context, in doBindHandlerInput) { } // BindObject binds the object for the specified pattern. -func (d *Domain) BindObject(pattern string, obj interface{}, methods ...string) { +func (d *Domain) BindObject(pattern string, obj any, methods ...string) { for domain := range d.domains { d.server.BindObject(pattern+"@"+domain, obj, methods...) } @@ -69,7 +69,7 @@ func (d *Domain) doBindObject(ctx context.Context, in doBindObjectInput) { } // BindObjectMethod binds the method for the specified pattern. -func (d *Domain) BindObjectMethod(pattern string, obj interface{}, method string) { +func (d *Domain) BindObjectMethod(pattern string, obj any, method string) { for domain := range d.domains { d.server.BindObjectMethod(pattern+"@"+domain, obj, method) } @@ -89,7 +89,7 @@ func (d *Domain) doBindObjectMethod(ctx context.Context, in doBindObjectMethodIn } // BindObjectRest binds the RESTful API for the specified pattern. -func (d *Domain) BindObjectRest(pattern string, obj interface{}) { +func (d *Domain) BindObjectRest(pattern string, obj any) { for domain := range d.domains { d.server.BindObjectRest(pattern+"@"+domain, obj) } diff --git a/net/ghttp/ghttp_server_log.go b/net/ghttp/ghttp_server_log.go index 49b498ad09f..73dc7c64d9c 100644 --- a/net/ghttp/ghttp_server_log.go +++ b/net/ghttp/ghttp_server_log.go @@ -30,7 +30,7 @@ func (s *Server) handleAccessLog(r *Request) { float64(r.LeaveTime.Sub(r.EnterTime).Milliseconds())/1000, r.GetClientIp(), r.Referer(), r.UserAgent(), ) - logger := instance.GetOrSetFuncLock(loggerInstanceKey, func() interface{} { + logger := instance.GetOrSetFuncLock(loggerInstanceKey, func() any { l := s.Logger() l.SetFile(s.config.AccessLogPattern) l.SetStdoutPrint(s.config.LogStdout) @@ -72,7 +72,7 @@ func (s *Server) handleErrorLog(err error, r *Request) { } else { content += ", " + err.Error() } - logger := instance.GetOrSetFuncLock(loggerInstanceKey, func() interface{} { + logger := instance.GetOrSetFuncLock(loggerInstanceKey, func() any { l := s.Logger() l.SetStack(false) l.SetFile(s.config.ErrorLogPattern) diff --git a/net/ghttp/ghttp_server_pprof.go b/net/ghttp/ghttp_server_pprof.go index 3477d68a61f..8f89b8cd554 100644 --- a/net/ghttp/ghttp_server_pprof.go +++ b/net/ghttp/ghttp_server_pprof.go @@ -61,7 +61,7 @@ func (p *utilPProf) Index(r *Request) { ctx = r.Context() profiles = runpprof.Profiles() action = r.Get("action").String() - data = map[string]interface{}{ + data = map[string]any{ "uri": strings.TrimRight(r.URL.Path, "/") + "/", "profiles": profiles, } diff --git a/net/ghttp/ghttp_server_router.go b/net/ghttp/ghttp_server_router.go index dd4e6640d50..5be10aee174 100644 --- a/net/ghttp/ghttp_server_router.go +++ b/net/ghttp/ghttp_server_router.go @@ -187,7 +187,7 @@ func (s *Server) doSetHandler( handler.Router.RegRule, handler.Router.RegNames = s.patternToRegular(uri) if _, ok := s.serveTree[domain]; !ok { - s.serveTree[domain] = make(map[string]interface{}) + s.serveTree[domain] = make(map[string]any) } // List array, very important for router registering. // There may be multiple lists adding into this array when searching from root to leaf. @@ -223,28 +223,28 @@ func (s *Server) doSetHandler( part = "*fuzz" // If it's a fuzzy node, it creates a "*list" item - which is a list - in the hash map. // All the sub router items from this fuzzy node will also be added to its "*list" item. - if v, ok := p.(map[string]interface{})["*list"]; !ok { + if v, ok := p.(map[string]any)["*list"]; !ok { newListForFuzzy := glist.New() - p.(map[string]interface{})["*list"] = newListForFuzzy + p.(map[string]any)["*list"] = newListForFuzzy lists = append(lists, newListForFuzzy) } else { lists = append(lists, v.(*glist.List)) } } // Make a new bucket for the current node. - if _, ok := p.(map[string]interface{})[part]; !ok { - p.(map[string]interface{})[part] = make(map[string]interface{}) + if _, ok := p.(map[string]any)[part]; !ok { + p.(map[string]any)[part] = make(map[string]any) } // Loop to next bucket. - p = p.(map[string]interface{})[part] + p = p.(map[string]any)[part] // The leaf is a hash map and must have an item named "*list", which contains the router item. // The leaf can be furthermore extended by adding more ket-value pairs into its map. // Note that the `v != "*fuzz"` comparison is required as the list might be added in the former // fuzzy checks. if i == len(array)-1 && part != "*fuzz" { - if v, ok := p.(map[string]interface{})["*list"]; !ok { + if v, ok := p.(map[string]any)["*list"]; !ok { leafList := glist.New() - p.(map[string]interface{})["*list"] = leafList + p.(map[string]any)["*list"] = leafList lists = append(lists, leafList) } else { lists = append(lists, v.(*glist.List)) diff --git a/net/ghttp/ghttp_server_router_group.go b/net/ghttp/ghttp_server_router_group.go index 449367b081c..fe4fdb0afdc 100644 --- a/net/ghttp/ghttp_server_router_group.go +++ b/net/ghttp/ghttp_server_router_group.go @@ -34,10 +34,10 @@ type ( group *RouterGroup bindType string pattern string - object interface{} // Can be handler, controller or object. - params []interface{} // Extra parameters for route registering depending on the type. - source string // Handler is a register at a certain source file path: line. - bound bool // Is this item bound to server? + object any // Can be handler, controller or object. + params []any // Extra parameters for route registering depending on the type. + source string // Handler is a register at a certain source file path: line. + bound bool // Is this item bound to server? } ) @@ -151,7 +151,7 @@ func (g *RouterGroup) Clone() *RouterGroup { } // Bind does batch route registering feature for a router group. -func (g *RouterGroup) Bind(handlerOrObject ...interface{}) *RouterGroup { +func (g *RouterGroup) Bind(handlerOrObject ...any) *RouterGroup { var ( ctx = context.TODO() group = g.Clone() @@ -181,7 +181,7 @@ func (g *RouterGroup) Bind(handlerOrObject ...interface{}) *RouterGroup { } // ALL register an http handler to give the route pattern and all http methods. -func (g *RouterGroup) ALL(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) ALL(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray( groupBindTypeHandler, defaultMethod+":"+pattern, @@ -191,66 +191,66 @@ func (g *RouterGroup) ALL(pattern string, object interface{}, params ...interfac } // ALLMap registers http handlers for http methods using map. -func (g *RouterGroup) ALLMap(m map[string]interface{}) { +func (g *RouterGroup) ALLMap(m map[string]any) { for pattern, object := range m { g.ALL(pattern, object) } } // Map registers http handlers for http methods using map. -func (g *RouterGroup) Map(m map[string]interface{}) { +func (g *RouterGroup) Map(m map[string]any) { for pattern, object := range m { g.preBindToLocalArray(groupBindTypeHandler, pattern, object) } } // GET registers an http handler to give the route pattern and the http method: GET. -func (g *RouterGroup) GET(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) GET(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeHandler, "GET:"+pattern, object, params...) } // PUT registers an http handler to give the route pattern and the http method: PUT. -func (g *RouterGroup) PUT(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) PUT(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeHandler, "PUT:"+pattern, object, params...) } // POST registers an http handler to give the route pattern and the http method: POST. -func (g *RouterGroup) POST(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) POST(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeHandler, "POST:"+pattern, object, params...) } // DELETE registers an http handler to give the route pattern and the http method: DELETE. -func (g *RouterGroup) DELETE(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) DELETE(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeHandler, "DELETE:"+pattern, object, params...) } // PATCH registers an http handler to give the route pattern and the http method: PATCH. -func (g *RouterGroup) PATCH(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) PATCH(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeHandler, "PATCH:"+pattern, object, params...) } // HEAD registers an http handler to give the route pattern and the http method: HEAD. -func (g *RouterGroup) HEAD(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) HEAD(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeHandler, "HEAD:"+pattern, object, params...) } // CONNECT registers an http handler to give the route pattern and the http method: CONNECT. -func (g *RouterGroup) CONNECT(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) CONNECT(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeHandler, "CONNECT:"+pattern, object, params...) } // OPTIONS register an http handler to give the route pattern and the http method: OPTIONS. -func (g *RouterGroup) OPTIONS(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) OPTIONS(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeHandler, "OPTIONS:"+pattern, object, params...) } // TRACE registers an http handler to give the route pattern and the http method: TRACE. -func (g *RouterGroup) TRACE(pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) TRACE(pattern string, object any, params ...any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeHandler, "TRACE:"+pattern, object, params...) } // REST registers an http handler to give the route pattern according to REST rule. -func (g *RouterGroup) REST(pattern string, object interface{}) *RouterGroup { +func (g *RouterGroup) REST(pattern string, object any) *RouterGroup { return g.Clone().preBindToLocalArray(groupBindTypeRest, pattern, object) } @@ -266,7 +266,7 @@ func (g *RouterGroup) Middleware(handlers ...HandlerFunc) *RouterGroup { } // preBindToLocalArray adds the route registering parameters to an internal variable array for lazily registering feature. -func (g *RouterGroup) preBindToLocalArray(bindType string, pattern string, object interface{}, params ...interface{}) *RouterGroup { +func (g *RouterGroup) preBindToLocalArray(bindType string, pattern string, object any, params ...any) *RouterGroup { _, file, line := gdebug.CallerWithFilter([]string{consts.StackFilterKeyForGoFrame}) preBindItems = append(preBindItems, &preBindItem{ group: g, diff --git a/net/ghttp/ghttp_server_router_hook.go b/net/ghttp/ghttp_server_router_hook.go index fcac4e3ca0d..4345f497981 100644 --- a/net/ghttp/ghttp_server_router_hook.go +++ b/net/ghttp/ghttp_server_router_hook.go @@ -111,7 +111,7 @@ func (r *Request) getHookHandlers(hook HookName) []*HandlerItemParsed { // niceCallHookHandler nicely calls the hook handler function, // which means it automatically catches and returns the possible panic error to // avoid goroutine crash. -func (s *Server) niceCallHookHandler(f HandlerFunc, r *Request) (err interface{}) { +func (s *Server) niceCallHookHandler(f HandlerFunc, r *Request) (err any) { defer func() { err = recover() }() diff --git a/net/ghttp/ghttp_server_router_serve.go b/net/ghttp/ghttp_server_router_serve.go index d034c98abcc..548a1096528 100644 --- a/net/ghttp/ghttp_server_router_serve.go +++ b/net/ghttp/ghttp_server_router_serve.go @@ -72,7 +72,7 @@ func (s *Server) getHandlersWithCache(r *Request) (parsedItems []*HandlerItemPar path = xUrlPath } var handlerCacheKey = s.serveHandlerKey(method, path, host) - value, err := s.serveCache.GetOrSetFunc(ctx, handlerCacheKey, func(ctx context.Context) (interface{}, error) { + value, err := s.serveCache.GetOrSetFunc(ctx, handlerCacheKey, func(ctx context.Context) (any, error) { parsedItems, serveItem, hasHook, hasServe = s.searchHandlers(method, path, host) if parsedItems != nil { return &handlerCacheItem{parsedItems, serveItem, hasHook, hasServe}, nil @@ -135,30 +135,30 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*Han lists := make([]*glist.List, 0, 16) for i, part := range array { // Add all lists of each node to the list array. - if v, ok := p.(map[string]interface{})["*list"]; ok { + if v, ok := p.(map[string]any)["*list"]; ok { lists = append(lists, v.(*glist.List)) } - if v, ok := p.(map[string]interface{})[part]; ok { + if v, ok := p.(map[string]any)[part]; ok { // Loop to the next node by certain key name. p = v if i == len(array)-1 { - if v, ok := p.(map[string]interface{})["*list"]; ok { + if v, ok := p.(map[string]any)["*list"]; ok { lists = append(lists, v.(*glist.List)) break } } - } else if v, ok := p.(map[string]interface{})["*fuzz"]; ok { + } else if v, ok := p.(map[string]any)["*fuzz"]; ok { // Loop to the next node by fuzzy node item. p = v } if i == len(array)-1 { // It here also checks the fuzzy item, // for rule case like: "/user/*action" matches to "/user". - if v, ok := p.(map[string]interface{})["*fuzz"]; ok { + if v, ok := p.(map[string]any)["*fuzz"]; ok { p = v } // The leaf must have a list item. It adds the list to the list array. - if v, ok := p.(map[string]interface{})["*list"]; ok { + if v, ok := p.(map[string]any)["*list"]; ok { lists = append(lists, v.(*glist.List)) } } diff --git a/net/ghttp/ghttp_server_service_handler.go b/net/ghttp/ghttp_server_service_handler.go index 7e248c75c5e..82515cebb02 100644 --- a/net/ghttp/ghttp_server_service_handler.go +++ b/net/ghttp/ghttp_server_service_handler.go @@ -23,7 +23,7 @@ import ( // Note that the parameter `handler` can be type of: // 1. func(*ghttp.Request) // 2. func(context.Context, BizRequest)(BizResponse, error) -func (s *Server) BindHandler(pattern string, handler interface{}) { +func (s *Server) BindHandler(pattern string, handler any) { var ctx = context.TODO() funcInfo, err := s.checkAndCreateFuncInfo(handler, "", "", "") if err != nil { @@ -146,7 +146,7 @@ func (s *Server) nameToUri(name string) string { } func (s *Server) checkAndCreateFuncInfo( - f interface{}, pkgPath, structName, methodName string, + f any, pkgPath, structName, methodName string, ) (funcInfo handlerFuncInfo, err error) { funcInfo = handlerFuncInfo{ Type: reflect.TypeOf(f), @@ -160,7 +160,7 @@ func (s *Server) checkAndCreateFuncInfo( var ( reflectType = funcInfo.Type inputObject reflect.Value - inputObjectPtr interface{} + inputObjectPtr any ) if reflectType.NumIn() != 2 || reflectType.NumOut() != 2 { if pkgPath != "" { @@ -197,8 +197,8 @@ func (s *Server) checkAndCreateFuncInfo( return } - if reflectType.In(1).Kind() != reflect.Ptr || - (reflectType.In(1).Kind() == reflect.Ptr && reflectType.In(1).Elem().Kind() != reflect.Struct) { + if reflectType.In(1).Kind() != reflect.Pointer || + (reflectType.In(1).Kind() == reflect.Pointer && reflectType.In(1).Elem().Kind() != reflect.Struct) { err = gerror.NewCodef( gcode.CodeInvalidParameter, `invalid handler: defined as "%s", but the second input parameter should be type of pointer to struct like "*BizReq"`, @@ -210,8 +210,8 @@ func (s *Server) checkAndCreateFuncInfo( // Do not enable this logic, as many users are already using none struct pointer type // as the first output parameter. /* - if reflectType.Out(0).Kind() != reflect.Ptr || - (reflectType.Out(0).Kind() == reflect.Ptr && reflectType.Out(0).Elem().Kind() != reflect.Struct) { + if reflectType.Out(0).Kind() != reflect.Pointer || + (reflectType.Out(0).Kind() == reflect.Pointer && reflectType.Out(0).Elem().Kind() != reflect.Struct) { err = gerror.NewCodef( gcode.CodeInvalidParameter, `invalid handler: defined as "%s", but the first output parameter should be type of pointer to struct like "*BizRes"`, @@ -250,7 +250,7 @@ func createRouterFunc(funcInfo handlerFuncInfo) func(r *Request) { ) if funcInfo.Type.NumIn() == 2 { var inputObject reflect.Value - if funcInfo.Type.In(1).Kind() == reflect.Ptr { + if funcInfo.Type.In(1).Kind() == reflect.Pointer { inputObject = reflect.New(funcInfo.Type.In(1).Elem()) r.error = r.Parse(inputObject.Interface()) } else { diff --git a/net/ghttp/ghttp_server_service_object.go b/net/ghttp/ghttp_server_service_object.go index f497ab30937..ef33ab7ced6 100644 --- a/net/ghttp/ghttp_server_service_object.go +++ b/net/ghttp/ghttp_server_service_object.go @@ -21,7 +21,7 @@ import ( // // The optional parameter `method` is used to specify the method to be registered, which // supports multiple method names; multiple methods are separated by char ',', case-sensitive. -func (s *Server) BindObject(pattern string, object interface{}, method ...string) { +func (s *Server) BindObject(pattern string, object any, method ...string) { var bindMethod = "" if len(method) > 0 { bindMethod = method[0] @@ -40,7 +40,7 @@ func (s *Server) BindObject(pattern string, object interface{}, method ...string // // The optional parameter `method` is used to specify the method to be registered, which // does not support multiple method names but only one, case-sensitive. -func (s *Server) BindObjectMethod(pattern string, object interface{}, method string) { +func (s *Server) BindObjectMethod(pattern string, object any, method string) { s.doBindObjectMethod(context.TODO(), doBindObjectMethodInput{ Prefix: "", Pattern: pattern, @@ -52,7 +52,7 @@ func (s *Server) BindObjectMethod(pattern string, object interface{}, method str } // BindObjectRest registers object in REST API styles to server with a specified pattern. -func (s *Server) BindObjectRest(pattern string, object interface{}) { +func (s *Server) BindObjectRest(pattern string, object any) { s.doBindObjectRest(context.TODO(), doBindObjectInput{ Prefix: "", Pattern: pattern, @@ -66,7 +66,7 @@ func (s *Server) BindObjectRest(pattern string, object interface{}) { type doBindObjectInput struct { Prefix string Pattern string - Object interface{} + Object any Method string Middleware []HandlerFunc Source string @@ -179,7 +179,7 @@ func (s *Server) doBindObject(ctx context.Context, in doBindObjectInput) { type doBindObjectMethodInput struct { Prefix string Pattern string - Object interface{} + Object any Method string Middleware []HandlerFunc Source string diff --git a/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go b/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go index 642e50901e8..9934efa44fd 100644 --- a/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_ctx_test.go @@ -305,10 +305,10 @@ func Test_Request_Form(t *testing.T) { r.Response.Write(r.GetForm("key", "defVal")) }) group.ALL("/GetFormMap", func(r *ghttp.Request) { - r.Response.Write(r.GetFormMap(map[string]interface{}{"key": "val"})) + r.Response.Write(r.GetFormMap(map[string]any{"key": "val"})) }) group.ALL("/GetFormMap1", func(r *ghttp.Request) { - r.Response.Write(r.GetFormMap(map[string]interface{}{"array": "val"})) + r.Response.Write(r.GetFormMap(map[string]any{"array": "val"})) }) group.ALL("/GetFormMapStrVar", func(r *ghttp.Request) { if r.Get("a") != nil { diff --git a/net/ghttp/ghttp_z_unit_feature_request_json_test.go b/net/ghttp/ghttp_z_unit_feature_request_json_test.go index d219d29b2bb..6d134abb854 100644 --- a/net/ghttp/ghttp_z_unit_feature_request_json_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_json_test.go @@ -96,11 +96,11 @@ func Test_Params_Json_Response(t *testing.T) { Error string `json:"error,omitempty"` } type ResponseJson struct { - Success bool `json:"success"` - Data interface{} `json:"data,omitempty"` - ExtData interface{} `json:"ext_data,omitempty"` - Paginate interface{} `json:"paginate,omitempty"` - Message Message `json:"message,omitempty"` + Success bool `json:"success"` + Data any `json:"data,omitempty"` + ExtData any `json:"ext_data,omitempty"` + Paginate any `json:"paginate,omitempty"` + Message Message `json:"message,omitempty"` } responseJson := &ResponseJson{ Success: true, @@ -117,11 +117,11 @@ func Test_Params_Json_Response(t *testing.T) { Error string `json:"error,omitempty"` } type ResponseJson struct { - Success bool `json:"success"` - Data interface{} `json:"data,omitempty"` - ExtData interface{} `json:"ext_data,omitempty"` - Paginate interface{} `json:"paginate,omitempty"` - Message *Message `json:"message,omitempty"` + Success bool `json:"success"` + Data any `json:"data,omitempty"` + ExtData any `json:"ext_data,omitempty"` + Paginate any `json:"paginate,omitempty"` + Message *Message `json:"message,omitempty"` } responseJson := ResponseJson{ Success: true, @@ -140,7 +140,7 @@ func Test_Params_Json_Response(t *testing.T) { client := g.Client() client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) - map1 := make(map[string]interface{}) + map1 := make(map[string]any) err1 := json.UnmarshalUseNumber([]byte(client.GetContent(ctx, "/json1")), &map1) t.Assert(err1, nil) t.Assert(len(map1), 4) @@ -149,7 +149,7 @@ func Test_Params_Json_Response(t *testing.T) { t.Assert(map1["password1"], "123") t.Assert(map1["password2"], "456") - map2 := make(map[string]interface{}) + map2 := make(map[string]any) err2 := json.UnmarshalUseNumber([]byte(client.GetContent(ctx, "/json2")), &map2) t.Assert(err2, nil) t.Assert(len(map2), 4) @@ -158,14 +158,14 @@ func Test_Params_Json_Response(t *testing.T) { t.Assert(map2["password1"], "123") t.Assert(map2["password2"], "456") - map3 := make(map[string]interface{}) + map3 := make(map[string]any) err3 := json.UnmarshalUseNumber([]byte(client.GetContent(ctx, "/json3")), &map3) t.Assert(err3, nil) t.Assert(len(map3), 2) t.Assert(map3["success"], "true") t.Assert(map3["message"], g.Map{"body": "测试", "code": 3, "error": "error"}) - map4 := make(map[string]interface{}) + map4 := make(map[string]any) err4 := json.UnmarshalUseNumber([]byte(client.GetContent(ctx, "/json4")), &map4) t.Assert(err4, nil) t.Assert(len(map4), 2) diff --git a/net/ghttp/ghttp_z_unit_feature_request_struct_test.go b/net/ghttp/ghttp_z_unit_feature_request_struct_test.go index a54e73ae434..aad6f704b08 100644 --- a/net/ghttp/ghttp_z_unit_feature_request_struct_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_struct_test.go @@ -22,7 +22,7 @@ func Test_Params_Parse(t *testing.T) { type User struct { Id int Name string - Map map[string]interface{} + Map map[string]any } s := g.Server(guid.S()) s.BindHandler("/parse", func(r *ghttp.Request) { diff --git a/net/ghttp/ghttp_z_unit_feature_request_test.go b/net/ghttp/ghttp_z_unit_feature_request_test.go index fb200d9381a..d79d5b89e62 100644 --- a/net/ghttp/ghttp_z_unit_feature_request_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_test.go @@ -56,7 +56,7 @@ func Test_Params_Basic(t *testing.T) { r.Response.Write(r.GetQuery("string").String()) } if r.GetQuery("map") != nil { - r.Response.Write(r.GetQueryMap()["map"].(map[string]interface{})["b"]) + r.Response.Write(r.GetQueryMap()["map"].(map[string]any)["b"]) } if r.GetQuery("a") != nil { r.Response.Write(r.GetQueryMapStrStr()["a"]) @@ -89,7 +89,7 @@ func Test_Params_Basic(t *testing.T) { r.Response.Write(r.Get("string").String()) } if r.Get("map") != nil { - r.Response.Write(r.GetMap()["map"].(map[string]interface{})["b"]) + r.Response.Write(r.GetMap()["map"].(map[string]any)["b"]) } if r.Get("a") != nil { r.Response.Write(r.GetMapStrStr()["a"]) @@ -123,7 +123,7 @@ func Test_Params_Basic(t *testing.T) { r.Response.Write(r.Get("string").String()) } if r.Get("map") != nil { - r.Response.Write(r.GetMap()["map"].(map[string]interface{})["b"]) + r.Response.Write(r.GetMap()["map"].(map[string]any)["b"]) } if r.Get("a") != nil { r.Response.Write(r.GetMapStrStr()["a"]) @@ -156,7 +156,7 @@ func Test_Params_Basic(t *testing.T) { r.Response.Write(r.Get("string").String()) } if r.Get("map") != nil { - r.Response.Write(r.GetMap()["map"].(map[string]interface{})["b"]) + r.Response.Write(r.GetMap()["map"].(map[string]any)["b"]) } if r.Get("a") != nil { r.Response.Write(r.GetMapStrStr()["a"]) @@ -189,7 +189,7 @@ func Test_Params_Basic(t *testing.T) { r.Response.Write(r.GetForm("string").String()) } if r.Get("map") != nil { - r.Response.Write(r.GetFormMap()["map"].(map[string]interface{})["b"]) + r.Response.Write(r.GetFormMap()["map"].(map[string]any)["b"]) } if r.Get("a") != nil { r.Response.Write(r.GetFormMapStrStr()["a"]) @@ -363,7 +363,7 @@ func Test_Params_Basic(t *testing.T) { func Test_Params_Header(t *testing.T) { s := g.Server(guid.S()) s.BindHandler("/header", func(r *ghttp.Request) { - r.Response.Write(map[string]interface{}{ + r.Response.Write(map[string]any{ "without-def": r.GetHeader("no-header"), "with-def": r.GetHeader("no-header", "my-default"), "x-custom-with": r.GetHeader("x-custom", "my-default"), @@ -451,16 +451,16 @@ func Test_Params_GetRequestMap(t *testing.T) { r.Response.Write(r.GetRequestMap()) }) s.BindHandler("/withKVMap", func(r *ghttp.Request) { - m := r.GetRequestMap(map[string]interface{}{"id": 2}) + m := r.GetRequestMap(map[string]any{"id": 2}) r.Response.Write(m["id"]) }) s.BindHandler("/paramsMapWithKVMap", func(r *ghttp.Request) { r.SetParam("name", "john") - m := r.GetRequestMap(map[string]interface{}{"id": 2}) + m := r.GetRequestMap(map[string]any{"id": 2}) r.Response.Write(m["id"]) }) s.BindHandler("/{name}.map", func(r *ghttp.Request) { - m := r.GetRequestMap(map[string]interface{}{"id": 2}) + m := r.GetRequestMap(map[string]any{"id": 2}) r.Response.Write(m["id"]) }) s.SetDumpRouterMap(false) @@ -738,7 +738,7 @@ func Test_Params_GetQueryMap(t *testing.T) { } }) s.BindHandler("/GetQueryMapWithKVMap", func(r *ghttp.Request) { - if m := r.GetQueryMap(map[string]interface{}{"id": 1}); len(m) > 0 { + if m := r.GetQueryMap(map[string]any{"id": 1}); len(m) > 0 { r.Response.Write(m["id"]) } }) diff --git a/net/ghttp/ghttp_z_unit_feature_response_test.go b/net/ghttp/ghttp_z_unit_feature_response_test.go index 6615baada73..e97c5ba9af2 100644 --- a/net/ghttp/ghttp_z_unit_feature_response_test.go +++ b/net/ghttp/ghttp_z_unit_feature_response_test.go @@ -271,7 +271,7 @@ func Test_Response_Write(t *testing.T) { r.Response.WriteJsonP(user) }) s.BindHandler("/WriteXml", func(r *ghttp.Request) { - m := map[string]interface{}{"name": "john"} + m := map[string]any{"name": "john"} if bytes, err := gxml.Encode(m); err == nil { r.Response.WriteXml(bytes) } diff --git a/net/ghttp/ghttp_z_unit_feature_router_group_test.go b/net/ghttp/ghttp_z_unit_feature_router_group_test.go index b5ac0eff0a8..7318c0d9b93 100644 --- a/net/ghttp/ghttp_z_unit_feature_router_group_test.go +++ b/net/ghttp/ghttp_z_unit_feature_router_group_test.go @@ -163,7 +163,7 @@ func Test_Router_Group_Map(t *testing.T) { } s := g.Server(guid.S()) s.Group("/", func(group *ghttp.RouterGroup) { - group.Map(map[string]interface{}{ + group.Map(map[string]any{ "Get: /test": testFuncGet, "Post:/test": testFuncPost, }) diff --git a/net/ghttp/ghttp_z_unit_issue_test.go b/net/ghttp/ghttp_z_unit_issue_test.go index 92f761ce963..a9d6a01bc9d 100644 --- a/net/ghttp/ghttp_z_unit_issue_test.go +++ b/net/ghttp/ghttp_z_unit_issue_test.go @@ -116,8 +116,8 @@ type Issue1653TestReq struct { } type Issue1653TestRes struct { - UUID string `json:"uuid"` - FeedBack interface{} `json:"feed_back"` + UUID string `json:"uuid"` + FeedBack any `json:"feed_back"` } type cIssue1653Foo struct{} diff --git a/net/goai/goai.go b/net/goai/goai.go index 9228b89dc44..51f8f53f492 100644 --- a/net/goai/goai.go +++ b/net/goai/goai.go @@ -97,10 +97,10 @@ func New() *OpenApiV3 { // AddInput is the structured parameter for function OpenApiV3.Add. type AddInput struct { - Path string // Path specifies the custom path if this is not configured in Meta of struct tag. - Prefix string // Prefix specifies the custom route path prefix, which will be added with the path tag in Meta of struct tag. - Method string // Method specifies the custom HTTP method if this is not configured in Meta of struct tag. - Object interface{} // Object can be an instance of struct or a route function. + Path string // Path specifies the custom path if this is not configured in Meta of struct tag. + Prefix string // Prefix specifies the custom route path prefix, which will be added with the path tag in Meta of struct tag. + Method string // Method specifies the custom HTTP method if this is not configured in Meta of struct tag. + Object any // Object can be an instance of struct or a route function. } // Add adds an instance of struct or a route function to OpenApiV3 definition implements. @@ -108,7 +108,7 @@ func (oai *OpenApiV3) Add(in AddInput) error { var ( reflectValue = reflect.ValueOf(in.Object) ) - for reflectValue.Kind() == reflect.Ptr { + for reflectValue.Kind() == reflect.Pointer { reflectValue = reflectValue.Elem() } switch reflectValue.Kind() { @@ -141,7 +141,7 @@ func (oai OpenApiV3) String() string { } func (oai *OpenApiV3) golangTypeToOAIType(t reflect.Type) string { - for t.Kind() == reflect.Ptr { + for t.Kind() == reflect.Pointer { t = t.Elem() } switch t.Kind() { @@ -204,7 +204,7 @@ func (oai *OpenApiV3) golangTypeToSchemaName(t reflect.Type) string { schemaName = gstr.TrimLeft(t.String(), "*") ) // Pointer type has no PkgPath. - for t.Kind() == reflect.Ptr { + for t.Kind() == reflect.Pointer { t = t.Elem() } if pkgPath = t.PkgPath(); pkgPath != "" && pkgPath != "." { diff --git a/net/goai/goai_config.go b/net/goai/goai_config.go index 9e7e54e0574..f9180ca7598 100644 --- a/net/goai/goai_config.go +++ b/net/goai/goai_config.go @@ -8,13 +8,13 @@ package goai // Config provides extra configuration feature for OpenApiV3 implements. type Config struct { - ReadContentTypes []string // ReadContentTypes specifies the default MIME types for consuming if MIME types are not configured. - WriteContentTypes []string // WriteContentTypes specifies the default MIME types for producing if MIME types are not configured. - CommonRequest interface{} // Common request structure for all paths. - CommonRequestDataField string // Common request field name to be replaced with certain business request structure. Eg: `Data`, `Request.`. - CommonResponse interface{} // Common response structure for all paths. - CommonResponseDataField string // Common response field name to be replaced with certain business response structure. Eg: `Data`, `Response.`. - IgnorePkgPath bool // Ignores package name for schema name. + ReadContentTypes []string // ReadContentTypes specifies the default MIME types for consuming if MIME types are not configured. + WriteContentTypes []string // WriteContentTypes specifies the default MIME types for producing if MIME types are not configured. + CommonRequest any // Common request structure for all paths. + CommonRequestDataField string // Common request field name to be replaced with certain business request structure. Eg: `Data`, `Request.`. + CommonResponse any // Common response structure for all paths. + CommonResponseDataField string // Common response field name to be replaced with certain business response structure. Eg: `Data`, `Response.`. + IgnorePkgPath bool // Ignores package name for schema name. } // fillWithDefaultValue fills configuration object of `oai` with default values if these are not configured. diff --git a/net/goai/goai_example.go b/net/goai/goai_example.go index 34ec816c29b..ac7e31472e2 100644 --- a/net/goai/goai_example.go +++ b/net/goai/goai_example.go @@ -18,10 +18,10 @@ import ( // Example is specified by OpenAPI/Swagger 3.0 standard. type Example struct { - Summary string `json:"summary,omitempty"` - Description string `json:"description,omitempty"` - Value interface{} `json:"value,omitempty"` - ExternalValue string `json:"externalValue,omitempty"` + Summary string `json:"summary,omitempty"` + Description string `json:"description,omitempty"` + Value any `json:"value,omitempty"` + ExternalValue string `json:"externalValue,omitempty"` } type Examples map[string]*ExampleRef @@ -47,7 +47,7 @@ func (e *Examples) applyExamplesFile(path string) error { if json == "" { return nil } - var data interface{} + var data any err := gjson.Unmarshal([]byte(json), &data) if err != nil { return err @@ -59,13 +59,13 @@ func (e *Examples) applyExamplesFile(path string) error { return nil } -func (e *Examples) applyExamplesData(data interface{}) error { +func (e *Examples) applyExamplesData(data any) error { if empty.IsNil(e) || empty.IsNil(data) { return nil } switch v := data.(type) { - case map[string]interface{}: + case map[string]any: for key, value := range v { (*e)[key] = &ExampleRef{ Value: &Example{ @@ -73,7 +73,7 @@ func (e *Examples) applyExamplesData(data interface{}) error { }, } } - case []interface{}: + case []any: for i, value := range v { (*e)[fmt.Sprintf("example %d", i+1)] = &ExampleRef{ Value: &Example{ diff --git a/net/goai/goai_external_docs.go b/net/goai/goai_external_docs.go index 2265865c0c5..f617d224f9a 100644 --- a/net/goai/goai_external_docs.go +++ b/net/goai/goai_external_docs.go @@ -18,7 +18,7 @@ type ExternalDocs struct { Description string `json:"description,omitempty"` } -func (ed *ExternalDocs) UnmarshalValue(value interface{}) error { +func (ed *ExternalDocs) UnmarshalValue(value any) error { var valueBytes = gconv.Bytes(value) if json.Valid(valueBytes) { return json.UnmarshalUseNumber(valueBytes, ed) diff --git a/net/goai/goai_link.go b/net/goai/goai_link.go index 0968c1b719e..f73d5167db7 100644 --- a/net/goai/goai_link.go +++ b/net/goai/goai_link.go @@ -12,12 +12,12 @@ import ( // Link is specified by OpenAPI/Swagger standard version 3.0. type Link struct { - OperationID string `json:"operationId,omitempty"` - OperationRef string `json:"operationRef,omitempty"` - Description string `json:"description,omitempty"` - Parameters map[string]interface{} `json:"parameters,omitempty"` - Server *Server `json:"server,omitempty"` - RequestBody interface{} `json:"requestBody,omitempty"` + OperationID string `json:"operationId,omitempty"` + OperationRef string `json:"operationRef,omitempty"` + Description string `json:"description,omitempty"` + Parameters map[string]any `json:"parameters,omitempty"` + Server *Server `json:"server,omitempty"` + RequestBody any `json:"requestBody,omitempty"` } type Links map[string]LinkRef diff --git a/net/goai/goai_mediatype.go b/net/goai/goai_mediatype.go index 4c2257df176..2fe6e79a6de 100644 --- a/net/goai/goai_mediatype.go +++ b/net/goai/goai_mediatype.go @@ -9,7 +9,7 @@ package goai // MediaType is specified by OpenAPI/Swagger 3.0 standard. type MediaType struct { Schema *SchemaRef `json:"schema,omitempty"` - Example interface{} `json:"example,omitempty"` + Example any `json:"example,omitempty"` Examples Examples `json:"examples,omitempty"` Encoding map[string]*Encoding `json:"encoding,omitempty"` } diff --git a/net/goai/goai_parameter.go b/net/goai/goai_parameter.go index 6b6e122c519..63a2883cd2e 100644 --- a/net/goai/goai_parameter.go +++ b/net/goai/goai_parameter.go @@ -25,7 +25,7 @@ type Parameter struct { Deprecated bool `json:"deprecated,omitempty"` Required bool `json:"required,omitempty"` Schema *SchemaRef `json:"schema,omitempty"` - Example interface{} `json:"example,omitempty"` + Example any `json:"example,omitempty"` Examples *Examples `json:"examples,omitempty"` Content *Content `json:"content,omitempty"` XExtensions XExtensions `json:"-"` diff --git a/net/goai/goai_path.go b/net/goai/goai_path.go index 2d5ac657681..0074ae457fb 100644 --- a/net/goai/goai_path.go +++ b/net/goai/goai_path.go @@ -49,10 +49,10 @@ const ( ) type addPathInput struct { - Path string // Precise route path. - Prefix string // Route path prefix. - Method string // Route method. - Function interface{} // Uniformed function. + Path string // Precise route path. + Prefix string // Route path prefix. + Method string // Route method. + Function any // Uniformed function. } func (oai *OpenApiV3) addPath(in addPathInput) error { @@ -73,12 +73,12 @@ func (oai *OpenApiV3) addPath(in addPathInput) error { outputObject reflect.Value ) // Create instance according input/output types. - if reflectType.In(1).Kind() == reflect.Ptr { + if reflectType.In(1).Kind() == reflect.Pointer { inputObject = reflect.New(reflectType.In(1).Elem()).Elem() } else { inputObject = reflect.New(reflectType.In(1)).Elem() } - if reflectType.Out(0).Kind() == reflect.Ptr { + if reflectType.Out(0).Kind() == reflect.Pointer { outputObject = reflect.New(reflectType.Out(0).Elem()).Elem() } else { outputObject = reflect.New(reflectType.Out(0)).Elem() @@ -324,7 +324,7 @@ func (oai *OpenApiV3) removeOperationDuplicatedProperties(operation Operation) { } var ( - duplicatedParameterNames []interface{} + duplicatedParameterNames []any dataField string ) @@ -372,7 +372,7 @@ func (oai *OpenApiV3) removeOperationDuplicatedProperties(operation Operation) { } } -func (oai *OpenApiV3) removeItemsFromArray(array []string, items []interface{}) []string { +func (oai *OpenApiV3) removeItemsFromArray(array []string, items []any) []string { arr := garray.NewStrArrayFrom(array) for _, item := range items { if value, ok := item.(string); ok { @@ -382,7 +382,7 @@ func (oai *OpenApiV3) removeItemsFromArray(array []string, items []interface{}) return arr.Slice() } -func (oai *OpenApiV3) doesStructHasNoFields(s interface{}) bool { +func (oai *OpenApiV3) doesStructHasNoFields(s any) bool { return reflect.TypeOf(s).NumField() == 0 } diff --git a/net/goai/goai_requestbody.go b/net/goai/goai_requestbody.go index d9c1858dbbb..ad729804c2c 100644 --- a/net/goai/goai_requestbody.go +++ b/net/goai/goai_requestbody.go @@ -35,7 +35,7 @@ func (r RequestBodyRef) MarshalJSON() ([]byte, error) { type getRequestSchemaRefInput struct { BusinessStructName string - RequestObject interface{} + RequestObject any RequestDataField string } diff --git a/net/goai/goai_response.go b/net/goai/goai_response.go index 1f81365f68f..36ff8ff3c7d 100644 --- a/net/goai/goai_response.go +++ b/net/goai/goai_response.go @@ -18,7 +18,7 @@ type EnhancedStatusCode = int // EnhancedStatusType is the structure for certain response status. // Currently, it only supports `Response` and `Examples`. // `Response` is the response structure -// `Examples` is the examples for the response, map[string]interface{}, []interface{} are supported. +// `Examples` is the examples for the response, map[string]any, []any are supported. type EnhancedStatusType struct { Response any Examples any diff --git a/net/goai/goai_response_ref.go b/net/goai/goai_response_ref.go index 683aa123335..2bb8daea25d 100644 --- a/net/goai/goai_response_ref.go +++ b/net/goai/goai_response_ref.go @@ -26,8 +26,8 @@ type Responses map[string]ResponseRef // object could be someObject.Interface() // There may be some difference between someObject.Type() and reflect.TypeOf(object). -func (oai *OpenApiV3) getResponseFromObject(data interface{}, isDefault bool) (*Response, error) { - var object interface{} +func (oai *OpenApiV3) getResponseFromObject(data any, isDefault bool) (*Response, error) { + var object any enhancedResponse, isEnhanced := data.(EnhancedStatusType) if isEnhanced { object = enhancedResponse.Response @@ -124,9 +124,9 @@ func (r ResponseRef) MarshalJSON() ([]byte, error) { } type getResponseSchemaRefInput struct { - BusinessStructName string // The business struct name. - CommonResponseObject interface{} // Common response object. - CommonResponseDataField string // Common response data field. + BusinessStructName string // The business struct name. + CommonResponseObject any // Common response object. + CommonResponseDataField string // Common response data field. } func (oai *OpenApiV3) getResponseSchemaRef(in getResponseSchemaRefInput) (*SchemaRef, error) { diff --git a/net/goai/goai_shema.go b/net/goai/goai_shema.go index 9d1e1e7126a..14105d53200 100644 --- a/net/goai/goai_shema.go +++ b/net/goai/goai_shema.go @@ -32,9 +32,9 @@ type Schema struct { Title string `json:"title,omitempty"` Format string `json:"format,omitempty"` Description string `json:"description,omitempty"` - Enum []interface{} `json:"enum,omitempty"` - Default interface{} `json:"default,omitempty"` - Example interface{} `json:"example,omitempty"` + Enum []any `json:"enum,omitempty"` + Default any `json:"default,omitempty"` + Example any `json:"example,omitempty"` ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"` UniqueItems bool `json:"uniqueItems,omitempty"` ExclusiveMin bool `json:"exclusiveMinimum,omitempty"` @@ -43,7 +43,7 @@ type Schema struct { ReadOnly bool `json:"readOnly,omitempty"` WriteOnly bool `json:"writeOnly,omitempty"` AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` - XML interface{} `json:"xml,omitempty"` + XML any `json:"xml,omitempty"` Deprecated bool `json:"deprecated,omitempty"` Min *float64 `json:"minimum,omitempty"` Max *float64 `json:"maximum,omitempty"` @@ -104,7 +104,7 @@ type Discriminator struct { // addSchema creates schemas with objects. // Note that the `object` can be array alias like: `type Res []Item`. -func (oai *OpenApiV3) addSchema(object ...interface{}) error { +func (oai *OpenApiV3) addSchema(object ...any) error { for _, v := range object { if err := oai.doAddSchemaSingle(v); err != nil { return err @@ -113,7 +113,7 @@ func (oai *OpenApiV3) addSchema(object ...interface{}) error { return nil } -func (oai *OpenApiV3) doAddSchemaSingle(object interface{}) error { +func (oai *OpenApiV3) doAddSchemaSingle(object any) error { if oai.Components.Schemas.refs == nil { oai.Components.Schemas.refs = gmap.NewListMap() } @@ -143,14 +143,14 @@ func (oai *OpenApiV3) doAddSchemaSingle(object interface{}) error { } // structToSchema converts and returns given struct object as Schema. -func (oai *OpenApiV3) structToSchema(object interface{}) (*Schema, error) { +func (oai *OpenApiV3) structToSchema(object any) (*Schema, error) { var ( tagMap = gmeta.Data(object) schema = &Schema{ Properties: createSchemas(), XExtensions: make(XExtensions), } - ignoreProperties []interface{} + ignoreProperties []any ) if len(tagMap) > 0 { if err := oai.tagMapToSchema(tagMap, schema); err != nil { diff --git a/net/goai/goai_shema_ref.go b/net/goai/goai_shema_ref.go index 63eef6894ba..825804a2c62 100644 --- a/net/goai/goai_shema_ref.go +++ b/net/goai/goai_shema_ref.go @@ -55,7 +55,7 @@ func (oai *OpenApiV3) newSchemaRefWithGolangType(golangType reflect.Type, tagMap ) if pkgPath == "" { switch golangType.Kind() { - case reflect.Ptr, reflect.Array, reflect.Slice: + case reflect.Pointer, reflect.Array, reflect.Slice: pkgPath = golangType.Elem().PkgPath() typeName = golangType.Elem().Name() default: @@ -65,7 +65,7 @@ func (oai *OpenApiV3) newSchemaRefWithGolangType(golangType reflect.Type, tagMap // Type enums. var typeId = fmt.Sprintf(`%s.%s`, pkgPath, typeName) if enums := gtag.GetEnumsByType(typeId); enums != "" { - schema.Enum = make([]interface{}, 0) + schema.Enum = make([]any, 0) if err = json.Unmarshal([]byte(enums), &schema.Enum); err != nil { return nil, err } @@ -128,7 +128,7 @@ func (oai *OpenApiV3) newSchemaRefWithGolangType(golangType reflect.Type, tagMap } case TypeObject: - for golangType.Kind() == reflect.Ptr { + for golangType.Kind() == reflect.Pointer { golangType = golangType.Elem() } switch golangType.Kind() { diff --git a/net/goai/goai_shemas.go b/net/goai/goai_shemas.go index d2e3020f8c3..057baf7fdc7 100644 --- a/net/goai/goai_shemas.go +++ b/net/goai/goai_shemas.go @@ -47,7 +47,7 @@ func (s *Schemas) Set(name string, ref SchemaRef) { s.refs.Set(name, ref) } -func (s *Schemas) Removes(names []interface{}) { +func (s *Schemas) Removes(names []any) { s.init() s.refs.Removes(names) } @@ -55,7 +55,7 @@ func (s *Schemas) Removes(names []interface{}) { func (s *Schemas) Map() map[string]SchemaRef { s.init() m := make(map[string]SchemaRef) - s.refs.Iterator(func(key, value interface{}) bool { + s.refs.Iterator(func(key, value any) bool { m[key.(string)] = value.(SchemaRef) return true }) @@ -64,7 +64,7 @@ func (s *Schemas) Map() map[string]SchemaRef { func (s *Schemas) Iterator(f func(key string, ref SchemaRef) bool) { s.init() - s.refs.Iterator(func(key, value interface{}) bool { + s.refs.Iterator(func(key, value any) bool { return f(key.(string), value.(SchemaRef)) }) } diff --git a/net/goai/goai_z_unit_issue_test.go b/net/goai/goai_z_unit_issue_test.go index 67fed9a26aa..4259045b06b 100644 --- a/net/goai/goai_z_unit_issue_test.go +++ b/net/goai/goai_z_unit_issue_test.go @@ -122,9 +122,9 @@ func Test_Issue3135(t *testing.T) { type Issue3889CommonRes struct { g.Meta `mime:"application/json"` - Code int `json:"code"` - Message string `json:"message"` - Data interface{} `json:"data"` + Code int `json:"code"` + Message string `json:"message"` + Data any `json:"data"` } type Issue3889Req struct { @@ -163,7 +163,7 @@ var Issue3889ErrorRes = map[int][]gcode.Code{ func (r Issue3889Res) EnhanceResponseStatus() map[goai.EnhancedStatusCode]goai.EnhancedStatusType { Codes401 := Issue3889ErrorRes[401] // iterate Codes401 to generate Examples - var Examples401 []interface{} + var Examples401 []any for _, code := range Codes401 { example := Issue3889CommonRes{ Code: code.Code(), diff --git a/net/goai/goai_z_unit_test.go b/net/goai/goai_z_unit_test.go index f7e5d53a44e..1c58610c8a0 100644 --- a/net/goai/goai_z_unit_test.go +++ b/net/goai/goai_z_unit_test.go @@ -266,9 +266,9 @@ func TestOpenApiV3_Add_AutoDetectIn(t *testing.T) { func TestOpenApiV3_CommonRequest(t *testing.T) { type CommonRequest struct { - Code int `json:"code" description:"Error code"` - Message string `json:"message" description:"Error message"` - Data interface{} `json:"data" description:"Result data for certain request according API definition"` + Code int `json:"code" description:"Error code"` + Message string `json:"message" description:"Error message"` + Data any `json:"data" description:"Result data for certain request according API definition"` } type Req struct { @@ -320,9 +320,9 @@ func TestOpenApiV3_CommonRequest(t *testing.T) { func TestOpenApiV3_CommonRequest_WithoutDataField_Setting(t *testing.T) { type CommonRequest struct { - Code int `json:"code" description:"Error code"` - Message string `json:"message" description:"Error message"` - Data interface{} `json:"data" description:"Result data for certain request according API definition"` + Code int `json:"code" description:"Error code"` + Message string `json:"message" description:"Error message"` + Data any `json:"data" description:"Result data for certain request according API definition"` } type PutReq struct { @@ -397,9 +397,9 @@ func TestOpenApiV3_CommonRequest_WithoutDataField_Setting(t *testing.T) { func TestOpenApiV3_CommonRequest_EmptyRequest(t *testing.T) { type CommonRequest struct { - Code int `json:"code" description:"Error code"` - Message string `json:"message" description:"Error message"` - Data interface{} `json:"data" description:"Result data for certain request according API definition"` + Code int `json:"code" description:"Error code"` + Message string `json:"message" description:"Error message"` + Data any `json:"data" description:"Result data for certain request according API definition"` } type Req struct { @@ -560,9 +560,9 @@ func TestOpenApiV3_CommonRequest_Files(t *testing.T) { func TestOpenApiV3_CommonResponse(t *testing.T) { type CommonResponse struct { - Code int `json:"code" description:"Error code"` - Message string `json:"message" description:"Error message"` - Data interface{} `json:"data" description:"Result data for certain request according API definition"` + Code int `json:"code" description:"Error code"` + Message string `json:"message" description:"Error message"` + Data any `json:"data" description:"Result data for certain request according API definition"` } type Req struct { @@ -619,9 +619,9 @@ func TestOpenApiV3_CommonResponse(t *testing.T) { func TestOpenApiV3_CommonResponse_WithoutDataField_Setting(t *testing.T) { type CommonResponse struct { - Code int `json:"code" description:"Error code"` - Message string `json:"message" description:"Error message"` - Data interface{} `json:"data" description:"Result data for certain request according API definition"` + Code int `json:"code" description:"Error code"` + Message string `json:"message" description:"Error message"` + Data any `json:"data" description:"Result data for certain request according API definition"` } type Req struct { @@ -673,9 +673,9 @@ func TestOpenApiV3_CommonResponse_WithoutDataField_Setting(t *testing.T) { func TestOpenApiV3_CommonResponse_EmptyResponse(t *testing.T) { type CommonResponse struct { - Code int `json:"code" description:"Error code"` - Message string `json:"message" description:"Error message"` - Data interface{} `json:"data" description:"Result data for certain request according API definition"` + Code int `json:"code" description:"Error code"` + Message string `json:"message" description:"Error message"` + Data any `json:"data" description:"Result data for certain request according API definition"` } type Req struct { @@ -1021,9 +1021,9 @@ func Test_Properties_In_Sequence(t *testing.T) { func TestOpenApiV3_Ignore_Parameter(t *testing.T) { type CommonResponse struct { - Code int `json:"code" description:"Error code"` - Message string `json:"message" description:"Error message"` - Data interface{} `json:"data" description:"Result data for certain request according API definition"` + Code int `json:"code" description:"Error code"` + Message string `json:"message" description:"Error message"` + Data any `json:"data" description:"Result data for certain request according API definition"` } type ProductSearchReq struct { gmeta.Meta `path:"/test" method:"get"` @@ -1193,9 +1193,9 @@ func Test_NameFromJsonTag(t *testing.T) { func TestOpenApiV3_PathSecurity(t *testing.T) { type CommonResponse struct { - Code int `json:"code" description:"Error code"` - Message string `json:"message" description:"Error message"` - Data interface{} `json:"data" description:"Result data for certain request according API definition"` + Code int `json:"code" description:"Error code"` + Message string `json:"message" description:"Error message"` + Data any `json:"data" description:"Result data for certain request according API definition"` } type Req struct { @@ -1297,7 +1297,7 @@ func Test_Enums(t *testing.T) { req = new(Req) ) err = gtag.SetGlobalEnums(gjson.MustEncodeString(g.Map{ - "github.com/gogf/gf/v2/net/goai_test.Status": []interface{}{StatusA, StatusB}, + "github.com/gogf/gf/v2/net/goai_test.Status": []any{StatusA, StatusB}, })) t.AssertNil(err) diff --git a/net/gsel/gsel.go b/net/gsel/gsel.go index ce28506dd08..e0d18fda079 100644 --- a/net/gsel/gsel.go +++ b/net/gsel/gsel.go @@ -58,7 +58,7 @@ type DoneInfo struct { // trailing metadata. // // The only supported type now is *orca_v1.LoadReport. - ServerLoad interface{} + ServerLoad any } // DoneInfoMD is a mapping from metadata keys to value array. diff --git a/net/gsvc/gsvc.go b/net/gsvc/gsvc.go index 348c9f5132c..df00087bfe3 100644 --- a/net/gsvc/gsvc.go +++ b/net/gsvc/gsvc.go @@ -103,7 +103,7 @@ type Endpoint interface { type Endpoints []Endpoint // Metadata stores custom key-value pairs. -type Metadata map[string]interface{} +type Metadata map[string]any // SearchInput is the input for service searching. type SearchInput struct { diff --git a/net/gsvc/gsvc_discovery.go b/net/gsvc/gsvc_discovery.go index a50c1208ef6..4f8b4570773 100644 --- a/net/gsvc/gsvc_discovery.go +++ b/net/gsvc/gsvc_discovery.go @@ -44,11 +44,11 @@ func GetAndWatchWithDiscovery(ctx context.Context, discovery Discovery, name str return nil, gerror.NewCodef(gcode.CodeInvalidParameter, `discovery cannot be nil`) } // Retrieve service map by discovery object. - watchedServiceMap := watchedMap.GetOrSetFunc(discovery, func() interface{} { + watchedServiceMap := watchedMap.GetOrSetFunc(discovery, func() any { return gmap.NewStrAnyMap(true) }).(*gmap.StrAnyMap) // Retrieve service by name. - storedService := watchedServiceMap.GetOrSetFuncLock(name, func() interface{} { + storedService := watchedServiceMap.GetOrSetFuncLock(name, func() any { var ( services []Service watcher Watcher diff --git a/net/gsvc/gsvc_metadata.go b/net/gsvc/gsvc_metadata.go index 015c599eb98..0737b276dae 100644 --- a/net/gsvc/gsvc_metadata.go +++ b/net/gsvc/gsvc_metadata.go @@ -11,12 +11,12 @@ import ( ) // Set sets key-value pair into metadata. -func (m Metadata) Set(key string, value interface{}) { +func (m Metadata) Set(key string, value any) { m[key] = value } // Sets sets key-value pairs into metadata. -func (m Metadata) Sets(kvs map[string]interface{}) { +func (m Metadata) Sets(kvs map[string]any) { for k, v := range kvs { m[k] = v } diff --git a/net/gtcp/gtcp_pool.go b/net/gtcp/gtcp_pool.go index 5d4135bb605..70b6ae735a6 100644 --- a/net/gtcp/gtcp_pool.go +++ b/net/gtcp/gtcp_pool.go @@ -36,9 +36,9 @@ var ( // NewPoolConn creates and returns a connection with pool feature. func NewPoolConn(addr string, timeout ...time.Duration) (*PoolConn, error) { - v := addressPoolMap.GetOrSetFuncLock(addr, func() interface{} { + v := addressPoolMap.GetOrSetFuncLock(addr, func() any { var pool *gpool.Pool - pool = gpool.New(defaultPoolExpire, func() (interface{}, error) { + pool = gpool.New(defaultPoolExpire, func() (any, error) { if conn, err := NewConn(addr, timeout...); err == nil { return &PoolConn{conn, pool, connStatusActive}, nil } else { diff --git a/net/gtcp/gtcp_server.go b/net/gtcp/gtcp_server.go index 010f6b1a222..e3d8ae77b2d 100644 --- a/net/gtcp/gtcp_server.go +++ b/net/gtcp/gtcp_server.go @@ -43,12 +43,12 @@ var serverMapping = gmap.NewStrAnyMap(true) // GetServer returns the TCP server with specified `name`, // or it returns a new normal TCP server named `name` if it does not exist. // The parameter `name` is used to specify the TCP server -func GetServer(name ...interface{}) *Server { +func GetServer(name ...any) *Server { serverName := defaultServer if len(name) > 0 && name[0] != "" { serverName = gconv.String(name[0]) } - return serverMapping.GetOrSetFuncLock(serverName, func() interface{} { + return serverMapping.GetOrSetFuncLock(serverName, func() any { return NewServer("", nil) }).(*Server) } diff --git a/net/gtrace/gtrace.go b/net/gtrace/gtrace.go index d1e72273bf7..5578a5e616c 100644 --- a/net/gtrace/gtrace.go +++ b/net/gtrace/gtrace.go @@ -126,13 +126,13 @@ func GetSpanID(ctx context.Context) string { // SetBaggageValue is a convenient function for adding one key-value pair to baggage. // Note that it uses attribute.Any to set the key-value pair. -func SetBaggageValue(ctx context.Context, key string, value interface{}) context.Context { +func SetBaggageValue(ctx context.Context, key string, value any) context.Context { return NewBaggage(ctx).SetValue(key, value) } // SetBaggageMap is a convenient function for adding map key-value pairs to baggage. // Note that it uses attribute.Any to set the key-value pair. -func SetBaggageMap(ctx context.Context, data map[string]interface{}) context.Context { +func SetBaggageMap(ctx context.Context, data map[string]any) context.Context { return NewBaggage(ctx).SetMap(data) } diff --git a/net/gtrace/gtrace_baggage.go b/net/gtrace/gtrace_baggage.go index 26a9eb86a11..dd69fea13ff 100644 --- a/net/gtrace/gtrace_baggage.go +++ b/net/gtrace/gtrace_baggage.go @@ -38,7 +38,7 @@ func (b *Baggage) Ctx() context.Context { // SetValue is a convenient function for adding one key-value pair to baggage. // Note that it uses attribute.Any to set the key-value pair. -func (b *Baggage) SetValue(key string, value interface{}) context.Context { +func (b *Baggage) SetValue(key string, value any) context.Context { member, _ := baggage.NewMember(key, gconv.String(value)) bag, _ := baggage.New(member) b.ctx = baggage.ContextWithBaggage(b.ctx, bag) @@ -47,7 +47,7 @@ func (b *Baggage) SetValue(key string, value interface{}) context.Context { // SetMap is a convenient function for adding map key-value pairs to baggage. // Note that it uses attribute.Any to set the key-value pair. -func (b *Baggage) SetMap(data map[string]interface{}) context.Context { +func (b *Baggage) SetMap(data map[string]any) context.Context { members := make([]baggage.Member, 0) for k, v := range data { member, _ := baggage.NewMember(k, gconv.String(v)) diff --git a/net/gtrace/gtrace_carrier.go b/net/gtrace/gtrace_carrier.go index e29d7007bc9..c1390d32e45 100644 --- a/net/gtrace/gtrace_carrier.go +++ b/net/gtrace/gtrace_carrier.go @@ -12,14 +12,14 @@ import ( ) // Carrier is the storage medium used by a TextMapPropagator. -type Carrier map[string]interface{} +type Carrier map[string]any // NewCarrier creates and returns a Carrier. -func NewCarrier(data ...map[string]interface{}) Carrier { +func NewCarrier(data ...map[string]any) Carrier { if len(data) > 0 && data[0] != nil { return data[0] } - return make(map[string]interface{}) + return make(map[string]any) } // Get returns the value associated with the passed key. diff --git a/net/gudp/gudp_server.go b/net/gudp/gudp_server.go index 0ace0996e9a..9a23e27723d 100644 --- a/net/gudp/gudp_server.go +++ b/net/gudp/gudp_server.go @@ -52,7 +52,7 @@ var ( ) // GetServer creates and returns an udp server instance with given name. -func GetServer(name ...interface{}) *Server { +func GetServer(name ...any) *Server { serverName := defaultServer if len(name) > 0 && name[0] != "" { serverName = gconv.String(name[0]) diff --git a/os/gbuild/gbuild.go b/os/gbuild/gbuild.go index b7afb9e1a2e..e5bf3264699 100644 --- a/os/gbuild/gbuild.go +++ b/os/gbuild/gbuild.go @@ -20,12 +20,12 @@ import ( // BuildInfo maintains the built info of the current binary. type BuildInfo struct { - GoFrame string // Built used GoFrame version. - Golang string // Built the used Golang version. - Git string // Built used git repo. commit id and datetime. - Time string // Built datetime. - Version string // Built version. - Data map[string]interface{} // All custom built data key-value pairs. + GoFrame string // Built used GoFrame version. + Golang string // Built the used Golang version. + Git string // Built used git repo. commit id and datetime. + Time string // Built datetime. + Version string // Built version. + Data map[string]any // All custom built data key-value pairs. } const ( @@ -37,8 +37,8 @@ const ( ) var ( - builtInVarStr = "" // Raw variable base64 string, which is injected by go build flags. - builtInVarMap = map[string]interface{}{} // Binary custom variable map decoded. + builtInVarStr = "" // Raw variable base64 string, which is injected by go build flags. + builtInVarMap = map[string]any{} // Binary custom variable map decoded. ) func init() { @@ -71,7 +71,7 @@ func Info() BuildInfo { } // Get retrieves and returns the build-in binary variable with given name. -func Get(name string, def ...interface{}) *gvar.Var { +func Get(name string, def ...any) *gvar.Var { if v, ok := builtInVarMap[name]; ok { return gvar.New(v) } @@ -82,6 +82,6 @@ func Get(name string, def ...interface{}) *gvar.Var { } // Data returns the custom build-in variables as the map. -func Data() map[string]interface{} { +func Data() map[string]any { return builtInVarMap } diff --git a/os/gbuild/gbuild_z_unit_test.go b/os/gbuild/gbuild_z_unit_test.go index 6cb5e8a2eac..3aeb6d8b14e 100644 --- a/os/gbuild/gbuild_z_unit_test.go +++ b/os/gbuild/gbuild_z_unit_test.go @@ -39,6 +39,6 @@ func Test_Get(t *testing.T) { func Test_Map(t *testing.T) { gtest.C(t, func(t *gtest.T) { - t.Assert(gbuild.Data(), map[string]interface{}{}) + t.Assert(gbuild.Data(), map[string]any{}) }) } diff --git a/os/gcache/gcache.go b/os/gcache/gcache.go index 892b2a03404..51a4b411e82 100644 --- a/os/gcache/gcache.go +++ b/os/gcache/gcache.go @@ -17,7 +17,7 @@ import ( ) // Func is the cache function that calculates and returns the value. -type Func = func(ctx context.Context) (value interface{}, err error) +type Func = func(ctx context.Context) (value any, err error) // DurationNoExpire represents the cache key-value pair that never expires. const DurationNoExpire = time.Duration(0) @@ -29,7 +29,7 @@ var defaultCache = New() // // It does not expire if `duration` == 0. // It deletes the keys of `data` if `duration` < 0 or given `value` is nil. -func Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error { +func Set(ctx context.Context, key any, value any, duration time.Duration) error { return defaultCache.Set(ctx, key, value, duration) } @@ -37,7 +37,7 @@ func Set(ctx context.Context, key interface{}, value interface{}, duration time. // // It does not expire if `duration` == 0. // It deletes the keys of `data` if `duration` < 0 or given `value` is nil. -func SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error { +func SetMap(ctx context.Context, data map[any]any, duration time.Duration) error { return defaultCache.SetMap(ctx, data, duration) } @@ -47,19 +47,19 @@ func SetMap(ctx context.Context, data map[interface{}]interface{}, duration time // // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil. -func SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (bool, error) { +func SetIfNotExist(ctx context.Context, key any, value any, duration time.Duration) (bool, error) { return defaultCache.SetIfNotExist(ctx, key, value, duration) } // SetIfNotExistFunc sets `key` with result of function `f` and returns true // if `key` does not exist in the cache, or else it does nothing and returns false if `key` already exists. // -// The parameter `value` can be type of `func() interface{}`, but it does nothing if its +// The parameter `value` can be type of `func() any`, but it does nothing if its // result is nil. // // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil. -func SetIfNotExistFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (bool, error) { +func SetIfNotExistFunc(ctx context.Context, key any, f Func, duration time.Duration) (bool, error) { return defaultCache.SetIfNotExistFunc(ctx, key, f, duration) } @@ -71,14 +71,14 @@ func SetIfNotExistFunc(ctx context.Context, key interface{}, f Func, duration ti // // Note that it differs from function `SetIfNotExistFunc` is that the function `f` is executed within // writing mutex lock for concurrent safety purpose. -func SetIfNotExistFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (bool, error) { +func SetIfNotExistFuncLock(ctx context.Context, key any, f Func, duration time.Duration) (bool, error) { return defaultCache.SetIfNotExistFuncLock(ctx, key, f, duration) } // Get retrieves and returns the associated value of given `key`. // It returns nil if it does not exist, or its value is nil, or it's expired. // If you would like to check if the `key` exists in the cache, it's better using function Contains. -func Get(ctx context.Context, key interface{}) (*gvar.Var, error) { +func Get(ctx context.Context, key any) (*gvar.Var, error) { return defaultCache.Get(ctx, key) } @@ -89,7 +89,7 @@ func Get(ctx context.Context, key interface{}) (*gvar.Var, error) { // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing // if `value` is a function and the function result is nil. -func GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (*gvar.Var, error) { +func GetOrSet(ctx context.Context, key any, value any, duration time.Duration) (*gvar.Var, error) { return defaultCache.GetOrSet(ctx, key, value, duration) } @@ -100,7 +100,7 @@ func GetOrSet(ctx context.Context, key interface{}, value interface{}, duration // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing // if `value` is a function and the function result is nil. -func GetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (*gvar.Var, error) { +func GetOrSetFunc(ctx context.Context, key any, f Func, duration time.Duration) (*gvar.Var, error) { return defaultCache.GetOrSetFunc(ctx, key, f, duration) } @@ -114,12 +114,12 @@ func GetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Du // // Note that it differs from function `GetOrSetFunc` is that the function `f` is executed within // writing mutex lock for concurrent safety purpose. -func GetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (*gvar.Var, error) { +func GetOrSetFuncLock(ctx context.Context, key any, f Func, duration time.Duration) (*gvar.Var, error) { return defaultCache.GetOrSetFuncLock(ctx, key, f, duration) } // Contains checks and returns true if `key` exists in the cache, or else returns false. -func Contains(ctx context.Context, key interface{}) (bool, error) { +func Contains(ctx context.Context, key any) (bool, error) { return defaultCache.Contains(ctx, key) } @@ -128,18 +128,18 @@ func Contains(ctx context.Context, key interface{}) (bool, error) { // Note that, // It returns 0 if the `key` does not expire. // It returns -1 if the `key` does not exist in the cache. -func GetExpire(ctx context.Context, key interface{}) (time.Duration, error) { +func GetExpire(ctx context.Context, key any) (time.Duration, error) { return defaultCache.GetExpire(ctx, key) } // Remove deletes one or more keys from cache, and returns its value. // If multiple keys are given, it returns the value of the last deleted item. -func Remove(ctx context.Context, keys ...interface{}) (value *gvar.Var, err error) { +func Remove(ctx context.Context, keys ...any) (value *gvar.Var, err error) { return defaultCache.Remove(ctx, keys...) } // Removes deletes `keys` in the cache. -func Removes(ctx context.Context, keys []interface{}) error { +func Removes(ctx context.Context, keys []any) error { return defaultCache.Removes(ctx, keys) } @@ -148,7 +148,7 @@ func Removes(ctx context.Context, keys []interface{}) error { // // It deletes the `key` if given `value` is nil. // It does nothing if `key` does not exist in the cache. -func Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) { +func Update(ctx context.Context, key any, value any) (oldValue *gvar.Var, exist bool, err error) { return defaultCache.Update(ctx, key, value) } @@ -156,7 +156,7 @@ func Update(ctx context.Context, key interface{}, value interface{}) (oldValue * // // It returns -1 and does nothing if the `key` does not exist in the cache. // It deletes the `key` if `duration` < 0. -func UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) { +func UpdateExpire(ctx context.Context, key any, duration time.Duration) (oldDuration time.Duration, err error) { return defaultCache.UpdateExpire(ctx, key, duration) } @@ -168,12 +168,12 @@ func Size(ctx context.Context) (int, error) { // Data returns a copy of all key-value pairs in the cache as map type. // Note that this function may lead lots of memory usage, you can implement this function // if necessary. -func Data(ctx context.Context) (map[interface{}]interface{}, error) { +func Data(ctx context.Context) (map[any]any, error) { return defaultCache.Data(ctx) } // Keys returns all keys in the cache as slice. -func Keys(ctx context.Context) ([]interface{}, error) { +func Keys(ctx context.Context) ([]any, error) { return defaultCache.Keys(ctx) } @@ -183,37 +183,37 @@ func KeyStrings(ctx context.Context) ([]string, error) { } // Values returns all values in the cache as slice. -func Values(ctx context.Context) ([]interface{}, error) { +func Values(ctx context.Context) ([]any, error) { return defaultCache.Values(ctx) } // MustGet acts like Get, but it panics if any error occurs. -func MustGet(ctx context.Context, key interface{}) *gvar.Var { +func MustGet(ctx context.Context, key any) *gvar.Var { return defaultCache.MustGet(ctx, key) } // MustGetOrSet acts like GetOrSet, but it panics if any error occurs. -func MustGetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) *gvar.Var { +func MustGetOrSet(ctx context.Context, key any, value any, duration time.Duration) *gvar.Var { return defaultCache.MustGetOrSet(ctx, key, value, duration) } // MustGetOrSetFunc acts like GetOrSetFunc, but it panics if any error occurs. -func MustGetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) *gvar.Var { +func MustGetOrSetFunc(ctx context.Context, key any, f Func, duration time.Duration) *gvar.Var { return defaultCache.MustGetOrSetFunc(ctx, key, f, duration) } // MustGetOrSetFuncLock acts like GetOrSetFuncLock, but it panics if any error occurs. -func MustGetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) *gvar.Var { +func MustGetOrSetFuncLock(ctx context.Context, key any, f Func, duration time.Duration) *gvar.Var { return defaultCache.MustGetOrSetFuncLock(ctx, key, f, duration) } // MustContains acts like Contains, but it panics if any error occurs. -func MustContains(ctx context.Context, key interface{}) bool { +func MustContains(ctx context.Context, key any) bool { return defaultCache.MustContains(ctx, key) } // MustGetExpire acts like GetExpire, but it panics if any error occurs. -func MustGetExpire(ctx context.Context, key interface{}) time.Duration { +func MustGetExpire(ctx context.Context, key any) time.Duration { return defaultCache.MustGetExpire(ctx, key) } @@ -223,12 +223,12 @@ func MustSize(ctx context.Context) int { } // MustData acts like Data, but it panics if any error occurs. -func MustData(ctx context.Context) map[interface{}]interface{} { +func MustData(ctx context.Context) map[any]any { return defaultCache.MustData(ctx) } // MustKeys acts like Keys, but it panics if any error occurs. -func MustKeys(ctx context.Context) []interface{} { +func MustKeys(ctx context.Context) []any { return defaultCache.MustKeys(ctx) } @@ -238,6 +238,6 @@ func MustKeyStrings(ctx context.Context) []string { } // MustValues acts like Values, but it panics if any error occurs. -func MustValues(ctx context.Context) []interface{} { +func MustValues(ctx context.Context) []any { return defaultCache.MustValues(ctx) } diff --git a/os/gcache/gcache_adapter.go b/os/gcache/gcache_adapter.go index 3c98011ba6f..d6f169b4de0 100644 --- a/os/gcache/gcache_adapter.go +++ b/os/gcache/gcache_adapter.go @@ -21,13 +21,13 @@ type Adapter interface { // // It does not expire if `duration` == 0. // It deletes the keys of `data` if `duration` < 0 or given `value` is nil. - Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error + Set(ctx context.Context, key any, value any, duration time.Duration) error // SetMap batch sets cache with key-value pairs by `data` map, which is expired after `duration`. // // It does not expire if `duration` == 0. // It deletes the keys of `data` if `duration` < 0 or given `value` is nil. - SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error + SetMap(ctx context.Context, data map[any]any, duration time.Duration) error // SetIfNotExist sets cache with `key`-`value` pair which is expired after `duration` // if `key` does not exist in the cache. It returns true the `key` does not exist in the @@ -35,17 +35,17 @@ type Adapter interface { // // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil. - SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (ok bool, err error) + SetIfNotExist(ctx context.Context, key any, value any, duration time.Duration) (ok bool, err error) // SetIfNotExistFunc sets `key` with result of function `f` and returns true // if `key` does not exist in the cache, or else it does nothing and returns false if `key` already exists. // - // The parameter `value` can be type of `func() interface{}`, but it does nothing if its + // The parameter `value` can be type of `func() any`, but it does nothing if its // result is nil. // // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil. - SetIfNotExistFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (ok bool, err error) + SetIfNotExistFunc(ctx context.Context, key any, f Func, duration time.Duration) (ok bool, err error) // SetIfNotExistFuncLock sets `key` with result of function `f` and returns true // if `key` does not exist in the cache, or else it does nothing and returns false if `key` already exists. @@ -55,12 +55,12 @@ type Adapter interface { // // Note that it differs from function `SetIfNotExistFunc` is that the function `f` is executed within // writing mutex lock for concurrent safety purpose. - SetIfNotExistFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (ok bool, err error) + SetIfNotExistFuncLock(ctx context.Context, key any, f Func, duration time.Duration) (ok bool, err error) // Get retrieves and returns the associated value of given `key`. // It returns nil if it does not exist, or its value is nil, or it's expired. // If you would like to check if the `key` exists in the cache, it's better using function Contains. - Get(ctx context.Context, key interface{}) (*gvar.Var, error) + Get(ctx context.Context, key any) (*gvar.Var, error) // GetOrSet retrieves and returns the value of `key`, or sets `key`-`value` pair and // returns `value` if `key` does not exist in the cache. The key-value pair expires @@ -69,7 +69,7 @@ type Adapter interface { // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing // if `value` is a function and the function result is nil. - GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (result *gvar.Var, err error) + GetOrSet(ctx context.Context, key any, value any, duration time.Duration) (result *gvar.Var, err error) // GetOrSetFunc retrieves and returns the value of `key`, or sets `key` with result of // function `f` and returns its result if `key` does not exist in the cache. The key-value @@ -78,7 +78,7 @@ type Adapter interface { // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing // if `value` is a function and the function result is nil. - GetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (result *gvar.Var, err error) + GetOrSetFunc(ctx context.Context, key any, f Func, duration time.Duration) (result *gvar.Var, err error) // GetOrSetFuncLock retrieves and returns the value of `key`, or sets `key` with result of // function `f` and returns its result if `key` does not exist in the cache. The key-value @@ -90,10 +90,10 @@ type Adapter interface { // // Note that it differs from function `GetOrSetFunc` is that the function `f` is executed within // writing mutex lock for concurrent safety purpose. - GetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (result *gvar.Var, err error) + GetOrSetFuncLock(ctx context.Context, key any, f Func, duration time.Duration) (result *gvar.Var, err error) // Contains checks and returns true if `key` exists in the cache, or else returns false. - Contains(ctx context.Context, key interface{}) (bool, error) + Contains(ctx context.Context, key any) (bool, error) // Size returns the number of items in the cache. Size(ctx context.Context) (size int, err error) @@ -101,37 +101,37 @@ type Adapter interface { // Data returns a copy of all key-value pairs in the cache as map type. // Note that this function may lead lots of memory usage, you can implement this function // if necessary. - Data(ctx context.Context) (data map[interface{}]interface{}, err error) + Data(ctx context.Context) (data map[any]any, err error) // Keys returns all keys in the cache as slice. - Keys(ctx context.Context) (keys []interface{}, err error) + Keys(ctx context.Context) (keys []any, err error) // Values returns all values in the cache as slice. - Values(ctx context.Context) (values []interface{}, err error) + Values(ctx context.Context) (values []any, err error) // Update updates the value of `key` without changing its expiration and returns the old value. // The returned value `exist` is false if the `key` does not exist in the cache. // // It deletes the `key` if given `value` is nil. // It does nothing if `key` does not exist in the cache. - Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) + Update(ctx context.Context, key any, value any) (oldValue *gvar.Var, exist bool, err error) // UpdateExpire updates the expiration of `key` and returns the old expiration duration value. // // It returns -1 and does nothing if the `key` does not exist in the cache. // It deletes the `key` if `duration` < 0. - UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) + UpdateExpire(ctx context.Context, key any, duration time.Duration) (oldDuration time.Duration, err error) // GetExpire retrieves and returns the expiration of `key` in the cache. // // Note that, // It returns 0 if the `key` does not expire. // It returns -1 if the `key` does not exist in the cache. - GetExpire(ctx context.Context, key interface{}) (time.Duration, error) + GetExpire(ctx context.Context, key any) (time.Duration, error) // Remove deletes one or more keys from cache, and returns its value. // If multiple keys are given, it returns the value of the last deleted item. - Remove(ctx context.Context, keys ...interface{}) (lastValue *gvar.Var, err error) + Remove(ctx context.Context, keys ...any) (lastValue *gvar.Var, err error) // Clear clears all data of the cache. // Note that this function is sensitive and should be carefully used. diff --git a/os/gcache/gcache_adapter_memory.go b/os/gcache/gcache_adapter_memory.go index aceb0dc39c7..2f80a019a61 100644 --- a/os/gcache/gcache_adapter_memory.go +++ b/os/gcache/gcache_adapter_memory.go @@ -31,8 +31,8 @@ type AdapterMemory struct { // Internal event item. type adapterMemoryEvent struct { - k interface{} // Key. - e int64 // Expire time in milliseconds. + k any // Key. + e int64 // Expire time in milliseconds. } const ( @@ -72,7 +72,7 @@ func doNewAdapterMemory() *AdapterMemory { // // It does not expire if `duration` == 0. // It deletes the keys of `data` if `duration` < 0 or given `value` is nil. -func (c *AdapterMemory) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error { +func (c *AdapterMemory) Set(ctx context.Context, key any, value any, duration time.Duration) error { defer c.handleLruKey(ctx, key) expireTime := c.getInternalExpire(duration) c.data.Set(key, memoryDataItem{ @@ -90,7 +90,7 @@ func (c *AdapterMemory) Set(ctx context.Context, key interface{}, value interfac // // It does not expire if `duration` == 0. // It deletes the keys of `data` if `duration` < 0 or given `value` is nil. -func (c *AdapterMemory) SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error { +func (c *AdapterMemory) SetMap(ctx context.Context, data map[any]any, duration time.Duration) error { var ( expireTime = c.getInternalExpire(duration) err = c.data.SetMap(data, expireTime) @@ -118,7 +118,7 @@ func (c *AdapterMemory) SetMap(ctx context.Context, data map[interface{}]interfa // // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil. -func (c *AdapterMemory) SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (bool, error) { +func (c *AdapterMemory) SetIfNotExist(ctx context.Context, key any, value any, duration time.Duration) (bool, error) { defer c.handleLruKey(ctx, key) isContained, err := c.Contains(ctx, key) if err != nil { @@ -136,12 +136,12 @@ func (c *AdapterMemory) SetIfNotExist(ctx context.Context, key interface{}, valu // SetIfNotExistFunc sets `key` with result of function `f` and returns true // if `key` does not exist in the cache, or else it does nothing and returns false if `key` already exists. // -// The parameter `value` can be type of `func() interface{}`, but it does nothing if its +// The parameter `value` can be type of `func() any`, but it does nothing if its // result is nil. // // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil. -func (c *AdapterMemory) SetIfNotExistFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (bool, error) { +func (c *AdapterMemory) SetIfNotExistFunc(ctx context.Context, key any, f Func, duration time.Duration) (bool, error) { defer c.handleLruKey(ctx, key) isContained, err := c.Contains(ctx, key) if err != nil { @@ -168,7 +168,7 @@ func (c *AdapterMemory) SetIfNotExistFunc(ctx context.Context, key interface{}, // // Note that it differs from function `SetIfNotExistFunc` is that the function `f` is executed within // writing mutex lock for concurrent safety purpose. -func (c *AdapterMemory) SetIfNotExistFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (bool, error) { +func (c *AdapterMemory) SetIfNotExistFuncLock(ctx context.Context, key any, f Func, duration time.Duration) (bool, error) { defer c.handleLruKey(ctx, key) isContained, err := c.Contains(ctx, key) if err != nil { @@ -186,7 +186,7 @@ func (c *AdapterMemory) SetIfNotExistFuncLock(ctx context.Context, key interface // Get retrieves and returns the associated value of given `key`. // It returns nil if it does not exist, or its value is nil, or it's expired. // If you would like to check if the `key` exists in the cache, it's better using function Contains. -func (c *AdapterMemory) Get(ctx context.Context, key interface{}) (*gvar.Var, error) { +func (c *AdapterMemory) Get(ctx context.Context, key any) (*gvar.Var, error) { item, ok := c.data.Get(key) if ok && !item.IsExpired() { c.handleLruKey(ctx, key) @@ -202,7 +202,7 @@ func (c *AdapterMemory) Get(ctx context.Context, key interface{}) (*gvar.Var, er // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing // if `value` is a function and the function result is nil. -func (c *AdapterMemory) GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (*gvar.Var, error) { +func (c *AdapterMemory) GetOrSet(ctx context.Context, key any, value any, duration time.Duration) (*gvar.Var, error) { defer c.handleLruKey(ctx, key) v, err := c.Get(ctx, key) if err != nil { @@ -221,7 +221,7 @@ func (c *AdapterMemory) GetOrSet(ctx context.Context, key interface{}, value int // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing // if `value` is a function and the function result is nil. -func (c *AdapterMemory) GetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (*gvar.Var, error) { +func (c *AdapterMemory) GetOrSetFunc(ctx context.Context, key any, f Func, duration time.Duration) (*gvar.Var, error) { defer c.handleLruKey(ctx, key) v, err := c.Get(ctx, key) if err != nil { @@ -250,7 +250,7 @@ func (c *AdapterMemory) GetOrSetFunc(ctx context.Context, key interface{}, f Fun // // Note that it differs from function `GetOrSetFunc` is that the function `f` is executed within // writing mutex lock for concurrent safety purpose. -func (c *AdapterMemory) GetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (*gvar.Var, error) { +func (c *AdapterMemory) GetOrSetFuncLock(ctx context.Context, key any, f Func, duration time.Duration) (*gvar.Var, error) { defer c.handleLruKey(ctx, key) v, err := c.Get(ctx, key) if err != nil { @@ -263,7 +263,7 @@ func (c *AdapterMemory) GetOrSetFuncLock(ctx context.Context, key interface{}, f } // Contains checks and returns true if `key` exists in the cache, or else returns false. -func (c *AdapterMemory) Contains(ctx context.Context, key interface{}) (bool, error) { +func (c *AdapterMemory) Contains(ctx context.Context, key any) (bool, error) { v, err := c.Get(ctx, key) if err != nil { return false, err @@ -276,7 +276,7 @@ func (c *AdapterMemory) Contains(ctx context.Context, key interface{}) (bool, er // Note that, // It returns 0 if the `key` does not expire. // It returns -1 if the `key` does not exist in the cache. -func (c *AdapterMemory) GetExpire(ctx context.Context, key interface{}) (time.Duration, error) { +func (c *AdapterMemory) GetExpire(ctx context.Context, key any) (time.Duration, error) { if item, ok := c.data.Get(key); ok { c.handleLruKey(ctx, key) return time.Duration(item.e-gtime.TimestampMilli()) * time.Millisecond, nil @@ -286,13 +286,13 @@ func (c *AdapterMemory) GetExpire(ctx context.Context, key interface{}) (time.Du // Remove deletes one or more keys from cache, and returns its value. // If multiple keys are given, it returns the value of the last deleted item. -func (c *AdapterMemory) Remove(ctx context.Context, keys ...interface{}) (*gvar.Var, error) { +func (c *AdapterMemory) Remove(ctx context.Context, keys ...any) (*gvar.Var, error) { defer c.lru.Remove(keys...) return c.doRemove(ctx, keys...) } -func (c *AdapterMemory) doRemove(_ context.Context, keys ...interface{}) (*gvar.Var, error) { - var removedKeys []interface{} +func (c *AdapterMemory) doRemove(_ context.Context, keys ...any) (*gvar.Var, error) { + var removedKeys []any removedKeys, value, err := c.data.Remove(keys...) if err != nil { return nil, err @@ -311,7 +311,7 @@ func (c *AdapterMemory) doRemove(_ context.Context, keys ...interface{}) (*gvar. // // It deletes the `key` if given `value` is nil. // It does nothing if `key` does not exist in the cache. -func (c *AdapterMemory) Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) { +func (c *AdapterMemory) Update(ctx context.Context, key any, value any) (oldValue *gvar.Var, exist bool, err error) { v, exist, err := c.data.Update(key, value) if exist { c.handleLruKey(ctx, key) @@ -323,7 +323,7 @@ func (c *AdapterMemory) Update(ctx context.Context, key interface{}, value inter // // It returns -1 and does nothing if the `key` does not exist in the cache. // It deletes the `key` if `duration` < 0. -func (c *AdapterMemory) UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) { +func (c *AdapterMemory) UpdateExpire(ctx context.Context, key any, duration time.Duration) (oldDuration time.Duration, err error) { newExpireTime := c.getInternalExpire(duration) oldDuration, err = c.data.UpdateExpire(key, newExpireTime) if err != nil { @@ -345,17 +345,17 @@ func (c *AdapterMemory) Size(ctx context.Context) (size int, err error) { } // Data returns a copy of all key-value pairs in the cache as map type. -func (c *AdapterMemory) Data(ctx context.Context) (map[interface{}]interface{}, error) { +func (c *AdapterMemory) Data(ctx context.Context) (map[any]any, error) { return c.data.Data() } // Keys returns all keys in the cache as slice. -func (c *AdapterMemory) Keys(ctx context.Context) ([]interface{}, error) { +func (c *AdapterMemory) Keys(ctx context.Context) ([]any, error) { return c.data.Keys() } // Values returns all values in the cache as slice. -func (c *AdapterMemory) Values(ctx context.Context) ([]interface{}, error) { +func (c *AdapterMemory) Values(ctx context.Context) ([]any, error) { return c.data.Values() } @@ -377,12 +377,12 @@ func (c *AdapterMemory) Close(ctx context.Context) error { // cache, which is expired after `duration`. // // It does not expire if `duration` == 0. -// The parameter `value` can be type of , but it does nothing if the +// The parameter `value` can be type of , but it does nothing if the // function result is nil. // // It doubly checks the `key` whether exists in the cache using mutex writing lock // before setting it to the cache. -func (c *AdapterMemory) doSetWithLockCheck(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (result *gvar.Var, err error) { +func (c *AdapterMemory) doSetWithLockCheck(ctx context.Context, key any, value any, duration time.Duration) (result *gvar.Var, err error) { expireTimestamp := c.getInternalExpire(duration) v, err := c.data.SetWithLock(ctx, key, value, expireTimestamp) c.eventList.PushBack(&adapterMemoryEvent{k: key, e: expireTimestamp}) @@ -452,7 +452,7 @@ func (c *AdapterMemory) syncEventAndClearExpired(ctx context.Context) { expireTime = currentEk - i*1000 if expireSet = c.expireSets.Get(expireTime); expireSet != nil { // Iterating the set to delete all keys in it. - expireSet.Iterator(func(key interface{}) bool { + expireSet.Iterator(func(key any) bool { c.deleteExpiredKey(key) // remove auto expired key for lru. c.lru.Remove(key) @@ -464,7 +464,7 @@ func (c *AdapterMemory) syncEventAndClearExpired(ctx context.Context) { } } -func (c *AdapterMemory) handleLruKey(ctx context.Context, keys ...interface{}) { +func (c *AdapterMemory) handleLruKey(ctx context.Context, keys ...any) { if c.lru == nil { return } @@ -477,7 +477,7 @@ func (c *AdapterMemory) handleLruKey(ctx context.Context, keys ...interface{}) { // clearByKey deletes the key-value pair with given `key`. // The parameter `force` specifies whether doing this deleting forcibly. -func (c *AdapterMemory) deleteExpiredKey(key interface{}) { +func (c *AdapterMemory) deleteExpiredKey(key any) { // Doubly check before really deleting it from cache. c.data.Delete(key) // Deleting its expiration time from `expireTimes`. diff --git a/os/gcache/gcache_adapter_memory_data.go b/os/gcache/gcache_adapter_memory_data.go index ddd0c5fae86..b12c7ee179e 100644 --- a/os/gcache/gcache_adapter_memory_data.go +++ b/os/gcache/gcache_adapter_memory_data.go @@ -15,19 +15,19 @@ import ( ) type memoryData struct { - mu sync.RWMutex // dataMu ensures the concurrent safety of underlying data map. - data map[interface{}]memoryDataItem // data is the underlying cache data which is stored in a hash table. + mu sync.RWMutex // dataMu ensures the concurrent safety of underlying data map. + data map[any]memoryDataItem // data is the underlying cache data which is stored in a hash table. } // memoryDataItem holds the internal cache item data. type memoryDataItem struct { - v interface{} // Value. - e int64 // Expire timestamp in milliseconds. + v any // Value. + e int64 // Expire timestamp in milliseconds. } func newMemoryData() *memoryData { return &memoryData{ - data: make(map[interface{}]memoryDataItem), + data: make(map[any]memoryDataItem), } } @@ -36,7 +36,7 @@ func newMemoryData() *memoryData { // // It deletes the `key` if given `value` is nil. // It does nothing if `key` does not exist in the cache. -func (d *memoryData) Update(key interface{}, value interface{}) (oldValue interface{}, exist bool, err error) { +func (d *memoryData) Update(key any, value any) (oldValue any, exist bool, err error) { d.mu.Lock() defer d.mu.Unlock() if item, ok := d.data[key]; ok { @@ -53,7 +53,7 @@ func (d *memoryData) Update(key interface{}, value interface{}) (oldValue interf // // It returns -1 and does nothing if the `key` does not exist in the cache. // It deletes the `key` if `duration` < 0. -func (d *memoryData) UpdateExpire(key interface{}, expireTime int64) (oldDuration time.Duration, err error) { +func (d *memoryData) UpdateExpire(key any, expireTime int64) (oldDuration time.Duration, err error) { d.mu.Lock() defer d.mu.Unlock() if item, ok := d.data[key]; ok { @@ -68,10 +68,10 @@ func (d *memoryData) UpdateExpire(key interface{}, expireTime int64) (oldDuratio // Remove deletes the one or more keys from cache, and returns its value. // If multiple keys are given, it returns the value of the deleted last item. -func (d *memoryData) Remove(keys ...interface{}) (removedKeys []interface{}, value interface{}, err error) { +func (d *memoryData) Remove(keys ...any) (removedKeys []any, value any, err error) { d.mu.Lock() defer d.mu.Unlock() - removedKeys = make([]interface{}, 0) + removedKeys = make([]any, 0) for _, key := range keys { item, ok := d.data[key] if ok { @@ -84,11 +84,11 @@ func (d *memoryData) Remove(keys ...interface{}) (removedKeys []interface{}, val } // Data returns a copy of all key-value pairs in the cache as map type. -func (d *memoryData) Data() (map[interface{}]interface{}, error) { +func (d *memoryData) Data() (map[any]any, error) { d.mu.RLock() defer d.mu.RUnlock() var ( - data = make(map[interface{}]interface{}, len(d.data)) + data = make(map[any]any, len(d.data)) nowMilli = gtime.TimestampMilli() ) for k, v := range d.data { @@ -100,11 +100,11 @@ func (d *memoryData) Data() (map[interface{}]interface{}, error) { } // Keys returns all keys in the cache as slice. -func (d *memoryData) Keys() ([]interface{}, error) { +func (d *memoryData) Keys() ([]any, error) { d.mu.RLock() defer d.mu.RUnlock() var ( - keys = make([]interface{}, 0, len(d.data)) + keys = make([]any, 0, len(d.data)) nowMilli = gtime.TimestampMilli() ) for k, v := range d.data { @@ -116,11 +116,11 @@ func (d *memoryData) Keys() ([]interface{}, error) { } // Values returns all values in the cache as slice. -func (d *memoryData) Values() ([]interface{}, error) { +func (d *memoryData) Values() ([]any, error) { d.mu.RLock() defer d.mu.RUnlock() var ( - values = make([]interface{}, 0, len(d.data)) + values = make([]any, 0, len(d.data)) nowMilli = gtime.TimestampMilli() ) for _, v := range d.data { @@ -149,17 +149,17 @@ func (d *memoryData) Size() (size int, err error) { func (d *memoryData) Clear() { d.mu.Lock() defer d.mu.Unlock() - d.data = make(map[interface{}]memoryDataItem) + d.data = make(map[any]memoryDataItem) } -func (d *memoryData) Get(key interface{}) (item memoryDataItem, ok bool) { +func (d *memoryData) Get(key any) (item memoryDataItem, ok bool) { d.mu.RLock() item, ok = d.data[key] d.mu.RUnlock() return } -func (d *memoryData) Set(key interface{}, value memoryDataItem) { +func (d *memoryData) Set(key any, value memoryDataItem) { d.mu.Lock() d.data[key] = value d.mu.Unlock() @@ -169,7 +169,7 @@ func (d *memoryData) Set(key interface{}, value memoryDataItem) { // // It does not expire if `duration` == 0. // It deletes the keys of `data` if `duration` < 0 or given `value` is nil. -func (d *memoryData) SetMap(data map[interface{}]interface{}, expireTime int64) error { +func (d *memoryData) SetMap(data map[any]any, expireTime int64) error { d.mu.Lock() for k, v := range data { d.data[k] = memoryDataItem{ @@ -181,7 +181,7 @@ func (d *memoryData) SetMap(data map[interface{}]interface{}, expireTime int64) return nil } -func (d *memoryData) SetWithLock(ctx context.Context, key interface{}, value interface{}, expireTimestamp int64) (interface{}, error) { +func (d *memoryData) SetWithLock(ctx context.Context, key any, value any, expireTimestamp int64) (any, error) { d.mu.Lock() defer d.mu.Unlock() var ( @@ -193,7 +193,7 @@ func (d *memoryData) SetWithLock(ctx context.Context, key interface{}, value int f, ok := value.(Func) if !ok { // Compatible with raw function value. - f, ok = value.(func(ctx context.Context) (value interface{}, err error)) + f, ok = value.(func(ctx context.Context) (value any, err error)) } if ok { if value, err = f(ctx); err != nil { @@ -207,7 +207,7 @@ func (d *memoryData) SetWithLock(ctx context.Context, key interface{}, value int return value, nil } -func (d *memoryData) Delete(key interface{}) { +func (d *memoryData) Delete(key any) { d.mu.Lock() defer d.mu.Unlock() delete(d.data, key) diff --git a/os/gcache/gcache_adapter_memory_expire_times.go b/os/gcache/gcache_adapter_memory_expire_times.go index 182b751142d..29611f4205c 100644 --- a/os/gcache/gcache_adapter_memory_expire_times.go +++ b/os/gcache/gcache_adapter_memory_expire_times.go @@ -11,30 +11,30 @@ import ( ) type memoryExpireTimes struct { - mu sync.RWMutex // expireTimeMu ensures the concurrent safety of expireTimes map. - expireTimes map[interface{}]int64 // expireTimes is the expiring key to its timestamp mapping, which is used for quick indexing and deleting. + mu sync.RWMutex // expireTimeMu ensures the concurrent safety of expireTimes map. + expireTimes map[any]int64 // expireTimes is the expiring key to its timestamp mapping, which is used for quick indexing and deleting. } func newMemoryExpireTimes() *memoryExpireTimes { return &memoryExpireTimes{ - expireTimes: make(map[interface{}]int64), + expireTimes: make(map[any]int64), } } -func (d *memoryExpireTimes) Get(key interface{}) (value int64) { +func (d *memoryExpireTimes) Get(key any) (value int64) { d.mu.RLock() value = d.expireTimes[key] d.mu.RUnlock() return } -func (d *memoryExpireTimes) Set(key interface{}, value int64) { +func (d *memoryExpireTimes) Set(key any, value int64) { d.mu.Lock() d.expireTimes[key] = value d.mu.Unlock() } -func (d *memoryExpireTimes) Delete(key interface{}) { +func (d *memoryExpireTimes) Delete(key any) { d.mu.Lock() delete(d.expireTimes, key) d.mu.Unlock() diff --git a/os/gcache/gcache_adapter_memory_lru.go b/os/gcache/gcache_adapter_memory_lru.go index cf7f71c438d..8473a88c459 100644 --- a/os/gcache/gcache_adapter_memory_lru.go +++ b/os/gcache/gcache_adapter_memory_lru.go @@ -33,7 +33,7 @@ func newMemoryLru(cap int) *memoryLru { } // Remove deletes the `key` FROM `lru`. -func (l *memoryLru) Remove(keys ...interface{}) { +func (l *memoryLru) Remove(keys ...any) { if l == nil { return } @@ -47,13 +47,13 @@ func (l *memoryLru) Remove(keys ...interface{}) { } // SaveAndEvict saves the keys into LRU, evicts and returns the spare keys. -func (l *memoryLru) SaveAndEvict(keys ...interface{}) (evictedKeys []interface{}) { +func (l *memoryLru) SaveAndEvict(keys ...any) (evictedKeys []any) { if l == nil { return } l.mu.Lock() defer l.mu.Unlock() - evictedKeys = make([]interface{}, 0) + evictedKeys = make([]any, 0) for _, key := range keys { if evictedKey := l.doSaveAndEvict(key); evictedKey != nil { evictedKeys = append(evictedKeys, evictedKey) @@ -62,7 +62,7 @@ func (l *memoryLru) SaveAndEvict(keys ...interface{}) (evictedKeys []interface{} return } -func (l *memoryLru) doSaveAndEvict(key interface{}) (evictedKey interface{}) { +func (l *memoryLru) doSaveAndEvict(key any) (evictedKey any) { var element *glist.Element if v := l.data.Get(key); v != nil { element = v.(*glist.Element) diff --git a/os/gcache/gcache_adapter_redis.go b/os/gcache/gcache_adapter_redis.go index 794556a454c..e0b876912d5 100644 --- a/os/gcache/gcache_adapter_redis.go +++ b/os/gcache/gcache_adapter_redis.go @@ -31,7 +31,7 @@ func NewAdapterRedis(redis *gredis.Redis) *AdapterRedis { // // It does not expire if `duration` == 0. // It deletes the keys of `data` if `duration` < 0 or given `value` is nil. -func (c *AdapterRedis) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (err error) { +func (c *AdapterRedis) Set(ctx context.Context, key any, value any, duration time.Duration) (err error) { redisKey := gconv.String(key) if value == nil || duration < 0 { _, err = c.redis.Del(ctx, redisKey) @@ -49,7 +49,7 @@ func (c *AdapterRedis) Set(ctx context.Context, key interface{}, value interface // // It does not expire if `duration` == 0. // It deletes the keys of `data` if `duration` < 0 or given `value` is nil. -func (c *AdapterRedis) SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error { +func (c *AdapterRedis) SetMap(ctx context.Context, data map[any]any, duration time.Duration) error { if len(data) == 0 { return nil } @@ -91,7 +91,7 @@ func (c *AdapterRedis) SetMap(ctx context.Context, data map[interface{}]interfac // // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil. -func (c *AdapterRedis) SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (bool, error) { +func (c *AdapterRedis) SetIfNotExist(ctx context.Context, key any, value any, duration time.Duration) (bool, error) { var ( err error redisKey = gconv.String(key) @@ -100,7 +100,7 @@ func (c *AdapterRedis) SetIfNotExist(ctx context.Context, key interface{}, value f, ok := value.(Func) if !ok { // Compatible with raw function value. - f, ok = value.(func(ctx context.Context) (value interface{}, err error)) + f, ok = value.(func(ctx context.Context) (value any, err error)) } if ok { if value, err = f(ctx); err != nil { @@ -137,12 +137,12 @@ func (c *AdapterRedis) SetIfNotExist(ctx context.Context, key interface{}, value // SetIfNotExistFunc sets `key` with result of function `f` and returns true // if `key` does not exist in the cache, or else it does nothing and returns false if `key` already exists. // -// The parameter `value` can be type of `func() interface{}`, but it does nothing if its +// The parameter `value` can be type of `func() any`, but it does nothing if its // result is nil. // // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil. -func (c *AdapterRedis) SetIfNotExistFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (ok bool, err error) { +func (c *AdapterRedis) SetIfNotExistFunc(ctx context.Context, key any, f Func, duration time.Duration) (ok bool, err error) { value, err := f(ctx) if err != nil { return false, err @@ -158,7 +158,7 @@ func (c *AdapterRedis) SetIfNotExistFunc(ctx context.Context, key interface{}, f // // Note that it differs from function `SetIfNotExistFunc` is that the function `f` is executed within // writing mutex lock for concurrent safety purpose. -func (c *AdapterRedis) SetIfNotExistFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (ok bool, err error) { +func (c *AdapterRedis) SetIfNotExistFuncLock(ctx context.Context, key any, f Func, duration time.Duration) (ok bool, err error) { value, err := f(ctx) if err != nil { return false, err @@ -168,7 +168,7 @@ func (c *AdapterRedis) SetIfNotExistFuncLock(ctx context.Context, key interface{ // Get retrieves and returns the associated value of given . // It returns nil if it does not exist or its value is nil. -func (c *AdapterRedis) Get(ctx context.Context, key interface{}) (*gvar.Var, error) { +func (c *AdapterRedis) Get(ctx context.Context, key any) (*gvar.Var, error) { return c.redis.Get(ctx, gconv.String(key)) } @@ -179,7 +179,7 @@ func (c *AdapterRedis) Get(ctx context.Context, key interface{}) (*gvar.Var, err // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing // if `value` is a function and the function result is nil. -func (c *AdapterRedis) GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (result *gvar.Var, err error) { +func (c *AdapterRedis) GetOrSet(ctx context.Context, key any, value any, duration time.Duration) (result *gvar.Var, err error) { result, err = c.Get(ctx, key) if err != nil { return nil, err @@ -197,7 +197,7 @@ func (c *AdapterRedis) GetOrSet(ctx context.Context, key interface{}, value inte // It does not expire if `duration` == 0. // It deletes the `key` if `duration` < 0 or given `value` is nil, but it does nothing // if `value` is a function and the function result is nil. -func (c *AdapterRedis) GetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) (result *gvar.Var, err error) { +func (c *AdapterRedis) GetOrSetFunc(ctx context.Context, key any, f Func, duration time.Duration) (result *gvar.Var, err error) { v, err := c.Get(ctx, key) if err != nil { return nil, err @@ -226,12 +226,12 @@ func (c *AdapterRedis) GetOrSetFunc(ctx context.Context, key interface{}, f Func // // Note that it differs from function `GetOrSetFunc` is that the function `f` is executed within // writing mutex lock for concurrent safety purpose. -func (c *AdapterRedis) GetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) (result *gvar.Var, err error) { +func (c *AdapterRedis) GetOrSetFuncLock(ctx context.Context, key any, f Func, duration time.Duration) (result *gvar.Var, err error) { return c.GetOrSetFunc(ctx, key, f, duration) } // Contains checks and returns true if `key` exists in the cache, or else returns false. -func (c *AdapterRedis) Contains(ctx context.Context, key interface{}) (bool, error) { +func (c *AdapterRedis) Contains(ctx context.Context, key any) (bool, error) { n, err := c.redis.Exists(ctx, gconv.String(key)) if err != nil { return false, err @@ -251,7 +251,7 @@ func (c *AdapterRedis) Size(ctx context.Context) (size int, err error) { // Data returns a copy of all key-value pairs in the cache as map type. // Note that this function may lead lots of memory usage, you can implement this function // if necessary. -func (c *AdapterRedis) Data(ctx context.Context) (map[interface{}]interface{}, error) { +func (c *AdapterRedis) Data(ctx context.Context) (map[any]any, error) { // Keys. keys, err := c.redis.Keys(ctx, "*") if err != nil { @@ -264,7 +264,7 @@ func (c *AdapterRedis) Data(ctx context.Context) (map[interface{}]interface{}, e return nil, err } // Type converting. - data := make(map[interface{}]interface{}) + data := make(map[any]any) for k, v := range m { data[k] = v.Val() } @@ -272,7 +272,7 @@ func (c *AdapterRedis) Data(ctx context.Context) (map[interface{}]interface{}, e } // Keys returns all keys in the cache as slice. -func (c *AdapterRedis) Keys(ctx context.Context) ([]interface{}, error) { +func (c *AdapterRedis) Keys(ctx context.Context) ([]any, error) { keys, err := c.redis.Keys(ctx, "*") if err != nil { return nil, err @@ -281,7 +281,7 @@ func (c *AdapterRedis) Keys(ctx context.Context) ([]interface{}, error) { } // Values returns all values in the cache as slice. -func (c *AdapterRedis) Values(ctx context.Context) ([]interface{}, error) { +func (c *AdapterRedis) Values(ctx context.Context) ([]any, error) { // Keys. keys, err := c.redis.Keys(ctx, "*") if err != nil { @@ -294,7 +294,7 @@ func (c *AdapterRedis) Values(ctx context.Context) ([]interface{}, error) { return nil, err } // Values. - var values []interface{} + var values []any for _, key := range keys { if v := m[key]; !v.IsNil() { values = append(values, v.Val()) @@ -308,7 +308,7 @@ func (c *AdapterRedis) Values(ctx context.Context) ([]interface{}, error) { // // It deletes the `key` if given `value` is nil. // It does nothing if `key` does not exist in the cache. -func (c *AdapterRedis) Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) { +func (c *AdapterRedis) Update(ctx context.Context, key any, value any) (oldValue *gvar.Var, exist bool, err error) { var ( v *gvar.Var oldPTTL int64 @@ -352,7 +352,7 @@ func (c *AdapterRedis) Update(ctx context.Context, key interface{}, value interf // // It returns -1 and does nothing if the `key` does not exist in the cache. // It deletes the `key` if `duration` < 0. -func (c *AdapterRedis) UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) { +func (c *AdapterRedis) UpdateExpire(ctx context.Context, key any, duration time.Duration) (oldDuration time.Duration, err error) { var ( v *gvar.Var oldPTTL int64 @@ -394,7 +394,7 @@ func (c *AdapterRedis) UpdateExpire(ctx context.Context, key interface{}, durati // Note that, // It returns 0 if the `key` does not expire. // It returns -1 if the `key` does not exist in the cache. -func (c *AdapterRedis) GetExpire(ctx context.Context, key interface{}) (time.Duration, error) { +func (c *AdapterRedis) GetExpire(ctx context.Context, key any) (time.Duration, error) { pttl, err := c.redis.PTTL(ctx, gconv.String(key)) if err != nil { return 0, err @@ -411,7 +411,7 @@ func (c *AdapterRedis) GetExpire(ctx context.Context, key interface{}) (time.Dur // Remove deletes the one or more keys from cache, and returns its value. // If multiple keys are given, it returns the value of the deleted last item. -func (c *AdapterRedis) Remove(ctx context.Context, keys ...interface{}) (lastValue *gvar.Var, err error) { +func (c *AdapterRedis) Remove(ctx context.Context, keys ...any) (lastValue *gvar.Var, err error) { if len(keys) == 0 { return nil, nil } diff --git a/os/gcache/gcache_cache.go b/os/gcache/gcache_cache.go index 939227731e1..6ae38ed3e2b 100644 --- a/os/gcache/gcache_cache.go +++ b/os/gcache/gcache_cache.go @@ -55,7 +55,7 @@ func (c *Cache) GetAdapter() Adapter { } // Removes deletes `keys` in the cache. -func (c *Cache) Removes(ctx context.Context, keys []interface{}) error { +func (c *Cache) Removes(ctx context.Context, keys []any) error { _, err := c.Remove(ctx, keys...) return err } diff --git a/os/gcache/gcache_cache_must.go b/os/gcache/gcache_cache_must.go index 65961a0018c..4fbe0906663 100644 --- a/os/gcache/gcache_cache_must.go +++ b/os/gcache/gcache_cache_must.go @@ -14,7 +14,7 @@ import ( ) // MustGet acts like Get, but it panics if any error occurs. -func (c *Cache) MustGet(ctx context.Context, key interface{}) *gvar.Var { +func (c *Cache) MustGet(ctx context.Context, key any) *gvar.Var { v, err := c.Get(ctx, key) if err != nil { panic(err) @@ -23,7 +23,7 @@ func (c *Cache) MustGet(ctx context.Context, key interface{}) *gvar.Var { } // MustGetOrSet acts like GetOrSet, but it panics if any error occurs. -func (c *Cache) MustGetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) *gvar.Var { +func (c *Cache) MustGetOrSet(ctx context.Context, key any, value any, duration time.Duration) *gvar.Var { v, err := c.GetOrSet(ctx, key, value, duration) if err != nil { panic(err) @@ -32,7 +32,7 @@ func (c *Cache) MustGetOrSet(ctx context.Context, key interface{}, value interfa } // MustGetOrSetFunc acts like GetOrSetFunc, but it panics if any error occurs. -func (c *Cache) MustGetOrSetFunc(ctx context.Context, key interface{}, f Func, duration time.Duration) *gvar.Var { +func (c *Cache) MustGetOrSetFunc(ctx context.Context, key any, f Func, duration time.Duration) *gvar.Var { v, err := c.GetOrSetFunc(ctx, key, f, duration) if err != nil { panic(err) @@ -41,7 +41,7 @@ func (c *Cache) MustGetOrSetFunc(ctx context.Context, key interface{}, f Func, d } // MustGetOrSetFuncLock acts like GetOrSetFuncLock, but it panics if any error occurs. -func (c *Cache) MustGetOrSetFuncLock(ctx context.Context, key interface{}, f Func, duration time.Duration) *gvar.Var { +func (c *Cache) MustGetOrSetFuncLock(ctx context.Context, key any, f Func, duration time.Duration) *gvar.Var { v, err := c.GetOrSetFuncLock(ctx, key, f, duration) if err != nil { panic(err) @@ -50,7 +50,7 @@ func (c *Cache) MustGetOrSetFuncLock(ctx context.Context, key interface{}, f Fun } // MustContains acts like Contains, but it panics if any error occurs. -func (c *Cache) MustContains(ctx context.Context, key interface{}) bool { +func (c *Cache) MustContains(ctx context.Context, key any) bool { v, err := c.Contains(ctx, key) if err != nil { panic(err) @@ -59,7 +59,7 @@ func (c *Cache) MustContains(ctx context.Context, key interface{}) bool { } // MustGetExpire acts like GetExpire, but it panics if any error occurs. -func (c *Cache) MustGetExpire(ctx context.Context, key interface{}) time.Duration { +func (c *Cache) MustGetExpire(ctx context.Context, key any) time.Duration { v, err := c.GetExpire(ctx, key) if err != nil { panic(err) @@ -77,7 +77,7 @@ func (c *Cache) MustSize(ctx context.Context) int { } // MustData acts like Data, but it panics if any error occurs. -func (c *Cache) MustData(ctx context.Context) map[interface{}]interface{} { +func (c *Cache) MustData(ctx context.Context) map[any]any { v, err := c.Data(ctx) if err != nil { panic(err) @@ -86,7 +86,7 @@ func (c *Cache) MustData(ctx context.Context) map[interface{}]interface{} { } // MustKeys acts like Keys, but it panics if any error occurs. -func (c *Cache) MustKeys(ctx context.Context) []interface{} { +func (c *Cache) MustKeys(ctx context.Context) []any { v, err := c.Keys(ctx) if err != nil { panic(err) @@ -104,7 +104,7 @@ func (c *Cache) MustKeyStrings(ctx context.Context) []string { } // MustValues acts like Values, but it panics if any error occurs. -func (c *Cache) MustValues(ctx context.Context) []interface{} { +func (c *Cache) MustValues(ctx context.Context) []any { v, err := c.Values(ctx) if err != nil { panic(err) diff --git a/os/gcache/gcache_z_example_cache_test.go b/os/gcache/gcache_z_example_cache_test.go index 64a5e012bec..715548ee980 100644 --- a/os/gcache/gcache_z_example_cache_test.go +++ b/os/gcache/gcache_z_example_cache_test.go @@ -105,7 +105,7 @@ func ExampleCache_SetMap() { // Of course, you can also easily use the gcache package method directly c := gcache.New() - // map[interface{}]interface{} + // map[any]any data := g.MapAnyAny{ "k1": "v1", "k2": "v2", @@ -352,14 +352,14 @@ func ExampleCache_GetOrSetFunc() { // GetOrSetFunc retrieves and returns the value of `key`, or sets `key` with result of function `f` // and returns its result if `key` does not exist in the cache. - c.GetOrSetFunc(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { + c.GetOrSetFunc(ctx, "k1", func(ctx context.Context) (value any, err error) { return "v1", nil }, 10000*time.Millisecond) v, _ := c.Get(ctx, "k1") fmt.Println(v) // If func returns nil, no action is taken - c.GetOrSetFunc(ctx, "k2", func(ctx context.Context) (value interface{}, err error) { + c.GetOrSetFunc(ctx, "k2", func(ctx context.Context) (value any, err error) { return nil, nil }, 10000*time.Millisecond) v1, _ := c.Get(ctx, "k2") @@ -375,14 +375,14 @@ func ExampleCache_GetOrSetFuncLock() { c := gcache.New() // Modify locking Note that the function `f` should be executed within writing mutex lock for concurrent safety purpose. - c.GetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { + c.GetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value any, err error) { return "v1", nil }, 0) v, _ := c.Get(ctx, "k1") fmt.Println(v) // Modification failed - c.GetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { + c.GetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value any, err error) { return "update v1", nil }, 0) v, _ = c.Get(ctx, "k1") @@ -528,13 +528,13 @@ func ExampleCache_MustGetOrSetFunc() { c := gcache.New() // MustGetOrSetFunc acts like GetOrSetFunc, but it panics if any error occurs. - c.MustGetOrSetFunc(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { + c.MustGetOrSetFunc(ctx, "k1", func(ctx context.Context) (value any, err error) { return "v1", nil }, 10000*time.Millisecond) v := c.MustGet(ctx, "k1") fmt.Println(v) - c.MustGetOrSetFunc(ctx, "k2", func(ctx context.Context) (value interface{}, err error) { + c.MustGetOrSetFunc(ctx, "k2", func(ctx context.Context) (value any, err error) { return nil, nil }, 10000*time.Millisecond) v1 := c.MustGet(ctx, "k2") @@ -551,14 +551,14 @@ func ExampleCache_MustGetOrSetFuncLock() { c := gcache.New() // MustGetOrSetFuncLock acts like GetOrSetFuncLock, but it panics if any error occurs. - c.MustGetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { + c.MustGetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value any, err error) { return "v1", nil }, 0) v := c.MustGet(ctx, "k1") fmt.Println(v) // Modification failed - c.MustGetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value interface{}, err error) { + c.MustGetOrSetFuncLock(ctx, "k1", func(ctx context.Context) (value any, err error) { return "update v1", nil }, 0) v = c.MustGet(ctx, "k1") diff --git a/os/gcache/gcache_z_unit_test.go b/os/gcache/gcache_z_unit_test.go index 4eba06475a0..55a3e48c5ce 100644 --- a/os/gcache/gcache_z_unit_test.go +++ b/os/gcache/gcache_z_unit_test.go @@ -235,7 +235,7 @@ func TestCache_SetIfNotExist(t *testing.T) { func TestCache_SetIfNotExistFunc(t *testing.T) { gtest.C(t, func(t *gtest.T) { cache := gcache.New() - exist, err := cache.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + exist, err := cache.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) t.AssertNil(err) @@ -244,7 +244,7 @@ func TestCache_SetIfNotExistFunc(t *testing.T) { v, _ := cache.Get(ctx, 1) t.Assert(v, 11) - exist, err = cache.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + exist, err = cache.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value any, err error) { return 22, nil }, 0) t.AssertNil(err) @@ -256,7 +256,7 @@ func TestCache_SetIfNotExistFunc(t *testing.T) { gtest.C(t, func(t *gtest.T) { gcache.Remove(ctx, g.Slice{1, 2, 3}...) - ok, err := gcache.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + ok, err := gcache.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) t.AssertNil(err) @@ -265,7 +265,7 @@ func TestCache_SetIfNotExistFunc(t *testing.T) { v, _ := gcache.Get(ctx, 1) t.Assert(v, 11) - ok, err = gcache.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + ok, err = gcache.SetIfNotExistFunc(ctx, 1, func(ctx context.Context) (value any, err error) { return 22, nil }, 0) t.AssertNil(err) @@ -279,7 +279,7 @@ func TestCache_SetIfNotExistFunc(t *testing.T) { func TestCache_SetIfNotExistFuncLock(t *testing.T) { gtest.C(t, func(t *gtest.T) { cache := gcache.New() - exist, err := cache.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + exist, err := cache.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) t.AssertNil(err) @@ -288,7 +288,7 @@ func TestCache_SetIfNotExistFuncLock(t *testing.T) { v, _ := cache.Get(ctx, 1) t.Assert(v, 11) - exist, err = cache.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + exist, err = cache.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value any, err error) { return 22, nil }, 0) t.AssertNil(err) @@ -300,7 +300,7 @@ func TestCache_SetIfNotExistFuncLock(t *testing.T) { gtest.C(t, func(t *gtest.T) { gcache.Remove(ctx, g.Slice{1, 2, 3}...) - exist, err := gcache.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + exist, err := gcache.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) t.AssertNil(err) @@ -309,7 +309,7 @@ func TestCache_SetIfNotExistFuncLock(t *testing.T) { v, _ := gcache.Get(ctx, 1) t.Assert(v, 11) - exist, err = gcache.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + exist, err = gcache.SetIfNotExistFuncLock(ctx, 1, func(ctx context.Context) (value any, err error) { return 22, nil }, 0) t.AssertNil(err) @@ -374,13 +374,13 @@ func TestCache_GetOrSet(t *testing.T) { func TestCache_GetOrSetFunc(t *testing.T) { gtest.C(t, func(t *gtest.T) { cache := gcache.New() - cache.GetOrSetFunc(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + cache.GetOrSetFunc(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) v, _ := cache.Get(ctx, 1) t.Assert(v, 11) - cache.GetOrSetFunc(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + cache.GetOrSetFunc(ctx, 1, func(ctx context.Context) (value any, err error) { return 111, nil }, 0) v, _ = cache.Get(ctx, 1) @@ -388,13 +388,13 @@ func TestCache_GetOrSetFunc(t *testing.T) { gcache.Remove(ctx, g.Slice{1, 2, 3}...) - gcache.GetOrSetFunc(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + gcache.GetOrSetFunc(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) v, _ = cache.Get(ctx, 1) t.Assert(v, 11) - gcache.GetOrSetFunc(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + gcache.GetOrSetFunc(ctx, 1, func(ctx context.Context) (value any, err error) { return 111, nil }, 0) v, _ = cache.Get(ctx, 1) @@ -405,26 +405,26 @@ func TestCache_GetOrSetFunc(t *testing.T) { func TestCache_GetOrSetFuncLock(t *testing.T) { gtest.C(t, func(t *gtest.T) { cache := gcache.New() - cache.GetOrSetFuncLock(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + cache.GetOrSetFuncLock(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) v, _ := cache.Get(ctx, 1) t.Assert(v, 11) - cache.GetOrSetFuncLock(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + cache.GetOrSetFuncLock(ctx, 1, func(ctx context.Context) (value any, err error) { return 111, nil }, 0) v, _ = cache.Get(ctx, 1) t.Assert(v, 11) gcache.Remove(ctx, g.Slice{1, 2, 3}...) - gcache.GetOrSetFuncLock(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + gcache.GetOrSetFuncLock(ctx, 1, func(ctx context.Context) (value any, err error) { return 11, nil }, 0) v, _ = cache.Get(ctx, 1) t.Assert(v, 11) - gcache.GetOrSetFuncLock(ctx, 1, func(ctx context.Context) (value interface{}, err error) { + gcache.GetOrSetFuncLock(ctx, 1, func(ctx context.Context) (value any, err error) { return 111, nil }, 0) v, _ = cache.Get(ctx, 1) @@ -581,13 +581,13 @@ func TestCache_Basic_Must(t *testing.T) { v = gcache.MustGet(ctx, 2) t.Assert(v, 22) - gcache.MustGetOrSetFunc(ctx, 3, func(ctx context.Context) (value interface{}, err error) { + gcache.MustGetOrSetFunc(ctx, 3, func(ctx context.Context) (value any, err error) { return 33, nil }, 0) v = gcache.MustGet(ctx, 3) t.Assert(v, 33) - gcache.GetOrSetFuncLock(ctx, 4, func(ctx context.Context) (value interface{}, err error) { + gcache.GetOrSetFuncLock(ctx, 4, func(ctx context.Context) (value any, err error) { return 44, nil }, 0) v = gcache.MustGet(ctx, 4) diff --git a/os/gcfg/gcfg.go b/os/gcfg/gcfg.go index f8357b65cfe..0768f8d5aad 100644 --- a/os/gcfg/gcfg.go +++ b/os/gcfg/gcfg.go @@ -58,7 +58,7 @@ func Instance(name ...string) *Config { if len(name) > 0 && name[0] != "" { instanceName = name[0] } - return localInstances.GetOrSetFuncLock(instanceName, func() interface{} { + return localInstances.GetOrSetFuncLock(instanceName, func() any { adapterFile, err := NewAdapterFile() if err != nil { intlog.Errorf(context.Background(), `%+v`, err) @@ -95,10 +95,10 @@ func (c *Config) Available(ctx context.Context, resource ...string) (ok bool) { // It returns nil if no value found by `pattern`. // // It returns a default value specified by `def` if value for `pattern` is not found. -func (c *Config) Get(ctx context.Context, pattern string, def ...interface{}) (*gvar.Var, error) { +func (c *Config) Get(ctx context.Context, pattern string, def ...any) (*gvar.Var, error) { var ( err error - value interface{} + value any ) value, err = c.adapter.Get(ctx, pattern) if err != nil { @@ -118,7 +118,7 @@ func (c *Config) Get(ctx context.Context, pattern string, def ...interface{}) (* // It returns the default value `def` if none of them exists. // // Fetching Rules: Environment arguments are in uppercase format, eg: GF_PACKAGE_VARIABLE. -func (c *Config) GetWithEnv(ctx context.Context, pattern string, def ...interface{}) (*gvar.Var, error) { +func (c *Config) GetWithEnv(ctx context.Context, pattern string, def ...any) (*gvar.Var, error) { value, err := c.Get(ctx, pattern) if err != nil && gerror.Code(err) != gcode.CodeNotFound { return nil, err @@ -140,7 +140,7 @@ func (c *Config) GetWithEnv(ctx context.Context, pattern string, def ...interfac // It returns the default value `def` if none of them exists. // // Fetching Rules: Command line arguments are in lowercase format, eg: gf.package.variable. -func (c *Config) GetWithCmd(ctx context.Context, pattern string, def ...interface{}) (*gvar.Var, error) { +func (c *Config) GetWithCmd(ctx context.Context, pattern string, def ...any) (*gvar.Var, error) { value, err := c.Get(ctx, pattern) if err != nil && gerror.Code(err) != gcode.CodeNotFound { return nil, err @@ -158,12 +158,12 @@ func (c *Config) GetWithCmd(ctx context.Context, pattern string, def ...interfac } // Data retrieves and returns all configuration data as map type. -func (c *Config) Data(ctx context.Context) (data map[string]interface{}, err error) { +func (c *Config) Data(ctx context.Context) (data map[string]any, err error) { return c.adapter.Data(ctx) } // MustGet acts as function Get, but it panics if error occurs. -func (c *Config) MustGet(ctx context.Context, pattern string, def ...interface{}) *gvar.Var { +func (c *Config) MustGet(ctx context.Context, pattern string, def ...any) *gvar.Var { v, err := c.Get(ctx, pattern, def...) if err != nil { panic(err) @@ -175,7 +175,7 @@ func (c *Config) MustGet(ctx context.Context, pattern string, def ...interface{} } // MustGetWithEnv acts as function GetWithEnv, but it panics if error occurs. -func (c *Config) MustGetWithEnv(ctx context.Context, pattern string, def ...interface{}) *gvar.Var { +func (c *Config) MustGetWithEnv(ctx context.Context, pattern string, def ...any) *gvar.Var { v, err := c.GetWithEnv(ctx, pattern, def...) if err != nil { panic(err) @@ -184,7 +184,7 @@ func (c *Config) MustGetWithEnv(ctx context.Context, pattern string, def ...inte } // MustGetWithCmd acts as function GetWithCmd, but it panics if error occurs. -func (c *Config) MustGetWithCmd(ctx context.Context, pattern string, def ...interface{}) *gvar.Var { +func (c *Config) MustGetWithCmd(ctx context.Context, pattern string, def ...any) *gvar.Var { v, err := c.GetWithCmd(ctx, pattern, def...) if err != nil { panic(err) @@ -193,7 +193,7 @@ func (c *Config) MustGetWithCmd(ctx context.Context, pattern string, def ...inte } // MustData acts as function Data, but it panics if error occurs. -func (c *Config) MustData(ctx context.Context) map[string]interface{} { +func (c *Config) MustData(ctx context.Context) map[string]any { v, err := c.Data(ctx) if err != nil { panic(err) diff --git a/os/gcfg/gcfg_adaper.go b/os/gcfg/gcfg_adaper.go index 50fdd6b9019..a73afc7a00b 100644 --- a/os/gcfg/gcfg_adaper.go +++ b/os/gcfg/gcfg_adaper.go @@ -21,10 +21,10 @@ type Adapter interface { // Pattern like: // "x.y.z" for map item. // "x.0.y" for slice item. - Get(ctx context.Context, pattern string) (value interface{}, err error) + Get(ctx context.Context, pattern string) (value any, err error) // Data retrieves and returns all configuration data in current resource as map. // Note that this function may lead lots of memory usage if configuration data is too large, // you can implement this function if necessary. - Data(ctx context.Context) (data map[string]interface{}, err error) + Data(ctx context.Context) (data map[string]any, err error) } diff --git a/os/gcfg/gcfg_adapter_content.go b/os/gcfg/gcfg_adapter_content.go index 587d2a2f00d..166c273746b 100644 --- a/os/gcfg/gcfg_adapter_content.go +++ b/os/gcfg/gcfg_adapter_content.go @@ -58,7 +58,7 @@ func (a *AdapterContent) Available(ctx context.Context, resource ...string) (ok // Pattern like: // "x.y.z" for map item. // "x.0.y" for slice item. -func (a *AdapterContent) Get(ctx context.Context, pattern string) (value interface{}, err error) { +func (a *AdapterContent) Get(ctx context.Context, pattern string) (value any, err error) { if a.jsonVar.IsNil() { return nil, nil } @@ -68,7 +68,7 @@ func (a *AdapterContent) Get(ctx context.Context, pattern string) (value interfa // Data retrieves and returns all configuration data in current resource as map. // Note that this function may lead lots of memory usage if configuration data is too large, // you can implement this function if necessary. -func (a *AdapterContent) Data(ctx context.Context) (data map[string]interface{}, err error) { +func (a *AdapterContent) Data(ctx context.Context) (data map[string]any, err error) { if a.jsonVar.IsNil() { return nil, nil } diff --git a/os/gcfg/gcfg_adapter_file.go b/os/gcfg/gcfg_adapter_file.go index 1a9a1f83a3c..2114bb7ddb8 100644 --- a/os/gcfg/gcfg_adapter_file.go +++ b/os/gcfg/gcfg_adapter_file.go @@ -137,7 +137,7 @@ func (a *AdapterFile) GetFileName() string { // "list.10", "array.0.name", "array.0.1.id". // // It returns a default value specified by `def` if value for `pattern` is not found. -func (a *AdapterFile) Get(ctx context.Context, pattern string) (value interface{}, err error) { +func (a *AdapterFile) Get(ctx context.Context, pattern string) (value any, err error) { j, err := a.getJson() if err != nil { return nil, err @@ -153,7 +153,7 @@ func (a *AdapterFile) Get(ctx context.Context, pattern string) (value interface{ // It is commonly used to update certain configuration values in runtime. // Note that it is not recommended using `Set` configuration at runtime as the configuration would be // automatically refreshed if the underlying configuration file changed. -func (a *AdapterFile) Set(pattern string, value interface{}) error { +func (a *AdapterFile) Set(pattern string, value any) error { j, err := a.getJson() if err != nil { return err @@ -165,7 +165,7 @@ func (a *AdapterFile) Set(pattern string, value interface{}) error { } // Data retrieves and returns all configuration data as map type. -func (a *AdapterFile) Data(ctx context.Context) (data map[string]interface{}, err error) { +func (a *AdapterFile) Data(ctx context.Context) (data map[string]any, err error) { j, err := a.getJson() if err != nil { return nil, err @@ -237,7 +237,7 @@ func (a *AdapterFile) getJson(fileNameOrPath ...string) (configJson *gjson.Json, usedFileNameOrPath = a.defaultFileNameOrPath } // It uses JSON map to cache specified configuration file content. - result := a.jsonMap.GetOrSetFuncLock(usedFileNameOrPath, func() interface{} { + result := a.jsonMap.GetOrSetFuncLock(usedFileNameOrPath, func() any { var ( content string filePath string diff --git a/os/gcfg/gcfg_adapter_file_content.go b/os/gcfg/gcfg_adapter_file_content.go index 4304d5709d4..834d7a1978c 100644 --- a/os/gcfg/gcfg_adapter_file_content.go +++ b/os/gcfg/gcfg_adapter_file_content.go @@ -20,7 +20,7 @@ func (a *AdapterFile) SetContent(content string, fileNameOrPath ...string) { usedFileNameOrPath = fileNameOrPath[0] } // Clear file cache for instances which cached `name`. - localInstances.LockFunc(func(m map[string]interface{}) { + localInstances.LockFunc(func(m map[string]any) { if customConfigContentMap.Contains(usedFileNameOrPath) { for _, v := range m { if configInstance, ok := v.(*Config); ok { @@ -52,7 +52,7 @@ func (a *AdapterFile) RemoveContent(fileNameOrPath ...string) { usedFileNameOrPath = fileNameOrPath[0] } // Clear file cache for instances which cached `name`. - localInstances.LockFunc(func(m map[string]interface{}) { + localInstances.LockFunc(func(m map[string]any) { if customConfigContentMap.Contains(usedFileNameOrPath) { for _, v := range m { if configInstance, ok := v.(*Config); ok { @@ -72,7 +72,7 @@ func (a *AdapterFile) RemoveContent(fileNameOrPath ...string) { func (a *AdapterFile) ClearContent() { customConfigContentMap.Clear() // Clear cache for all instances. - localInstances.LockFunc(func(m map[string]interface{}) { + localInstances.LockFunc(func(m map[string]any) { for _, v := range m { if configInstance, ok := v.(*Config); ok { if fileConfig, ok := configInstance.GetAdapter().(*AdapterFile); ok { diff --git a/os/gcfg/gcfg_z_unit_basic_test.go b/os/gcfg/gcfg_z_unit_basic_test.go index ff034766072..cf5ebd26f6c 100644 --- a/os/gcfg/gcfg_z_unit_basic_test.go +++ b/os/gcfg/gcfg_z_unit_basic_test.go @@ -140,8 +140,8 @@ func Test_SetFileName(t *testing.T) { t.AssertEQ(c.MustGet(ctx, "array").Ints(), []int{1, 2, 3}) t.AssertEQ(c.MustGet(ctx, "array").Strings(), []string{"1", "2", "3"}) - t.AssertEQ(c.MustGet(ctx, "array").Interfaces(), []interface{}{1, 2, 3}) - t.AssertEQ(c.MustGet(ctx, "redis").Map(), map[string]interface{}{ + t.AssertEQ(c.MustGet(ctx, "array").Interfaces(), []any{1, 2, 3}) + t.AssertEQ(c.MustGet(ctx, "redis").Map(), map[string]any{ "disk": "127.0.0.1:6379,0", "cache": "127.0.0.1:6379,1", }) diff --git a/os/gcmd/gcmd.go b/os/gcmd/gcmd.go index b73644e913e..3ac54eb83bd 100644 --- a/os/gcmd/gcmd.go +++ b/os/gcmd/gcmd.go @@ -73,7 +73,7 @@ func GetArgAll() []string { // Fetching Rules: // 1. Command line arguments are in lowercase format, eg: gf.`package name`.; // 2. Environment arguments are in uppercase format, eg: GF_`package name`_; -func GetOptWithEnv(key string, def ...interface{}) *gvar.Var { +func GetOptWithEnv(key string, def ...any) *gvar.Var { cmdKey := utils.FormatCmdKey(key) if command.ContainsOpt(cmdKey) { return gvar.New(GetOpt(cmdKey)) diff --git a/os/gcmd/gcmd_command.go b/os/gcmd/gcmd_command.go index 80c824da3a8..db1ca419be5 100644 --- a/os/gcmd/gcmd_command.go +++ b/os/gcmd/gcmd_command.go @@ -42,7 +42,7 @@ type internalCommandAttributes struct { type Function func(ctx context.Context, parser *Parser) (err error) // FuncWithValue is similar like Func but with output parameters that can interact with command caller. -type FuncWithValue func(ctx context.Context, parser *Parser) (out interface{}, err error) +type FuncWithValue func(ctx context.Context, parser *Parser) (out any, err error) // Argument is the command value that are used by certain command. type Argument struct { @@ -107,7 +107,7 @@ func (c *Command) doAddCommand(command *Command) error { } // AddObject adds one or more sub-commands to current command using struct object. -func (c *Command) AddObject(objects ...interface{}) error { +func (c *Command) AddObject(objects ...any) error { var commands []*Command for _, object := range objects { rootCommand, err := NewFromObject(object) diff --git a/os/gcmd/gcmd_command_object.go b/os/gcmd/gcmd_command_object.go index f98820591fe..0eceb314c52 100644 --- a/os/gcmd/gcmd_command_object.go +++ b/os/gcmd/gcmd_command_object.go @@ -34,7 +34,7 @@ var ( ) // NewFromObject creates and returns a root command object using given object. -func NewFromObject(object interface{}) (rootCmd *Command, err error) { +func NewFromObject(object any) (rootCmd *Command, err error) { switch c := object.(type) { case Command: return &c, nil @@ -139,7 +139,7 @@ func methodToRootCmdWhenNameEqual(rootCmd *Command, methodCmd *Command) { // The `object` is the Meta attribute from business object, and the `name` is the command name, // commonly from method name, which is used when no name tag is defined in Meta. -func newCommandFromObjectMeta(object interface{}, name string) (command *Command, err error) { +func newCommandFromObjectMeta(object any, name string) (command *Command, err error) { var metaData = gmeta.Data(object) if err = gconv.Scan(metaData, &command); err != nil { return @@ -180,7 +180,7 @@ func newCommandFromObjectMeta(object interface{}, name string) (command *Command } func newCommandFromMethod( - object interface{}, method reflect.Method, methodValue reflect.Value, methodType reflect.Type, + object any, method reflect.Method, methodValue reflect.Value, methodType reflect.Type, ) (command *Command, err error) { // Necessary validation for input/output parameters and naming. if methodType.NumIn() != 2 || methodType.NumOut() != 2 { @@ -235,7 +235,7 @@ func newCommandFromMethod( } var inputObject reflect.Value - if methodType.In(1).Kind() == reflect.Ptr { + if methodType.In(1).Kind() == reflect.Pointer { inputObject = reflect.New(methodType.In(1).Elem()).Elem() } else { inputObject = reflect.New(methodType.In(1)).Elem() @@ -257,7 +257,7 @@ func newCommandFromMethod( // ============================================================================================= // Create function that has value return. // ============================================================================================= - command.FuncWithValue = func(ctx context.Context, parser *Parser) (out interface{}, err error) { + command.FuncWithValue = func(ctx context.Context, parser *Parser) (out any, err error) { ctx = context.WithValue(ctx, CtxKeyParser, parser) var ( data = gconv.Map(parser.GetOptAll()) @@ -269,7 +269,7 @@ func newCommandFromMethod( argIndex = value.(int) } if data == nil { - data = map[string]interface{}{} + data = map[string]any{} } // Handle orphan options. for _, arg := range command.Arguments { @@ -309,7 +309,7 @@ func newCommandFromMethod( intlog.PrintFunc(ctx, func() string { return fmt.Sprintf(`input command data map: %s`, gjson.MustEncode(data)) }) - if inputObject.Kind() == reflect.Ptr { + if inputObject.Kind() == reflect.Pointer { err = gconv.StructTag(data, inputObject.Interface(), priorityTag) } else { err = gconv.StructTag(data, inputObject.Addr().Interface(), priorityTag) @@ -342,7 +342,7 @@ func newCommandFromMethod( return } -func newArgumentsFromInput(object interface{}) (args []Argument, err error) { +func newArgumentsFromInput(object any) (args []Argument, err error) { var ( fields []gstructs.Field nameSet = gset.NewStrSet() @@ -409,7 +409,7 @@ func newArgumentsFromInput(object interface{}) (args []Argument, err error) { } // mergeDefaultStructValue merges the request parameters with default values from struct tag definition. -func mergeDefaultStructValue(data map[string]interface{}, pointer interface{}) error { +func mergeDefaultStructValue(data map[string]any, pointer any) error { tagFields, err := gstructs.TagFields(pointer, defaultValueTags) if err != nil { return err @@ -417,7 +417,7 @@ func mergeDefaultStructValue(data map[string]interface{}, pointer interface{}) e if len(tagFields) > 0 { var ( foundKey string - foundValue interface{} + foundValue any ) for _, field := range tagFields { var ( diff --git a/os/gcmd/gcmd_command_run.go b/os/gcmd/gcmd_command_run.go index 1f4c4bd063c..c8de329603d 100644 --- a/os/gcmd/gcmd_command_run.go +++ b/os/gcmd/gcmd_command_run.go @@ -37,7 +37,7 @@ func (c *Command) Run(ctx context.Context) { // RunWithValue calls custom function in os.Args that bound to this command with value output. // It exits this process with exit code 1 if any error occurs. -func (c *Command) RunWithValue(ctx context.Context) (value interface{}) { +func (c *Command) RunWithValue(ctx context.Context) (value any) { value, err := c.RunWithValueError(ctx) if err != nil { var ( @@ -71,12 +71,12 @@ func (c *Command) RunWithError(ctx context.Context) (err error) { } // RunWithValueError calls custom function in os.Args that bound to this command with value and error output. -func (c *Command) RunWithValueError(ctx context.Context) (value interface{}, err error) { +func (c *Command) RunWithValueError(ctx context.Context) (value any, err error) { return c.RunWithSpecificArgs(ctx, os.Args) } // RunWithSpecificArgs calls custom function in specific args that bound to this command with value and error output. -func (c *Command) RunWithSpecificArgs(ctx context.Context, args []string) (value interface{}, err error) { +func (c *Command) RunWithSpecificArgs(ctx context.Context, args []string) (value any, err error) { if len(args) == 0 { return nil, gerror.NewCode(gcode.CodeInvalidParameter, "args can not be empty!") } @@ -112,7 +112,7 @@ func (c *Command) RunWithSpecificArgs(ctx context.Context, args []string) (value return } -func (c *Command) doRun(ctx context.Context, args []string, parser *Parser) (value interface{}, err error) { +func (c *Command) doRun(ctx context.Context, args []string, parser *Parser) (value any, err error) { defer func() { if exception := recover(); exception != nil { if v, ok := exception.(error); ok && gerror.HasStack(v) { diff --git a/os/gcmd/gcmd_parser.go b/os/gcmd/gcmd_parser.go index f2794542648..7d35cd62a08 100644 --- a/os/gcmd/gcmd_parser.go +++ b/os/gcmd/gcmd_parser.go @@ -212,7 +212,7 @@ func (p *Parser) setOptionValue(name, value string) { } // GetOpt returns the option value named `name` as gvar.Var. -func (p *Parser) GetOpt(name string, def ...interface{}) *gvar.Var { +func (p *Parser) GetOpt(name string, def ...any) *gvar.Var { if p == nil { return nil } @@ -257,7 +257,7 @@ func (p *Parser) GetArgAll() []string { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (p *Parser) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "parsedArgs": p.parsedArgs, "parsedOptions": p.parsedOptions, "passedOptions": p.passedOptions, diff --git a/os/gcmd/gcmd_scan.go b/os/gcmd/gcmd_scan.go index d29296b18c5..4c54c1f0c19 100644 --- a/os/gcmd/gcmd_scan.go +++ b/os/gcmd/gcmd_scan.go @@ -16,13 +16,13 @@ import ( ) // Scan prints `info` to stdout, reads and returns user input, which stops by '\n'. -func Scan(info ...interface{}) string { +func Scan(info ...any) string { fmt.Print(info...) return readline() } // Scanf prints `info` to stdout with `format`, reads and returns user input, which stops by '\n'. -func Scanf(format string, info ...interface{}) string { +func Scanf(format string, info ...any) string { fmt.Printf(format, info...) return readline() } diff --git a/os/gcmd/gcmd_z_unit_test.go b/os/gcmd/gcmd_z_unit_test.go index 605b0b3fae6..c648e7627a1 100644 --- a/os/gcmd/gcmd_z_unit_test.go +++ b/os/gcmd/gcmd_z_unit_test.go @@ -246,19 +246,19 @@ func Test_Command_NotFound(t *testing.T) { } c1 := &gcmd.Command{ Name: "c1", - FuncWithValue: func(ctx context.Context, parser *gcmd.Parser) (interface{}, error) { + FuncWithValue: func(ctx context.Context, parser *gcmd.Parser) (any, error) { return nil, nil }, } c21 := &gcmd.Command{ Name: "c21", - FuncWithValue: func(ctx context.Context, parser *gcmd.Parser) (interface{}, error) { + FuncWithValue: func(ctx context.Context, parser *gcmd.Parser) (any, error) { return nil, nil }, } c22 := &gcmd.Command{ Name: "c22", - FuncWithValue: func(ctx context.Context, parser *gcmd.Parser) (interface{}, error) { + FuncWithValue: func(ctx context.Context, parser *gcmd.Parser) (any, error) { return nil, nil }, } diff --git a/os/gcron/gcron_cron.go b/os/gcron/gcron_cron.go index 2588de4c071..c9bd97cdfb1 100644 --- a/os/gcron/gcron_cron.go +++ b/os/gcron/gcron_cron.go @@ -214,7 +214,7 @@ func (c *Cron) Size() int { // Entries return all timed tasks as slice(order by registered time asc). func (c *Cron) Entries() []*Entry { - array := garray.NewSortedArraySize(c.entries.Size(), func(v1, v2 interface{}) int { + array := garray.NewSortedArraySize(c.entries.Size(), func(v1, v2 any) int { entry1 := v1.(*Entry) entry2 := v2.(*Entry) if entry1.RegisterTime.Nanosecond() > entry2.RegisterTime.Nanosecond() { @@ -222,13 +222,13 @@ func (c *Cron) Entries() []*Entry { } return -1 }, true) - c.entries.RLockFunc(func(m map[string]interface{}) { + c.entries.RLockFunc(func(m map[string]any) { for _, v := range m { array.Add(v.(*Entry)) } }) entries := make([]*Entry, array.Len()) - array.RLockFunc(func(array []interface{}) { + array.RLockFunc(func(array []any) { for k, v := range array { entries[k] = v.(*Entry) } diff --git a/os/gcron/gcron_entry.go b/os/gcron/gcron_entry.go index cbededcce8f..dd3ed72e610 100644 --- a/os/gcron/gcron_entry.go +++ b/os/gcron/gcron_entry.go @@ -187,13 +187,13 @@ func (e *Entry) getJobNameWithPattern() string { return fmt.Sprintf(`%s(%s)`, e.jobName, e.schedule.pattern) } -func (e *Entry) logDebugf(ctx context.Context, format string, v ...interface{}) { +func (e *Entry) logDebugf(ctx context.Context, format string, v ...any) { if logger := e.cron.GetLogger(); logger != nil { logger.Debugf(ctx, format, v...) } } -func (e *Entry) logErrorf(ctx context.Context, format string, v ...interface{}) { +func (e *Entry) logErrorf(ctx context.Context, format string, v ...any) { logger := e.cron.GetLogger() if logger == nil { logger = glog.DefaultLogger() diff --git a/os/genv/genv.go b/os/genv/genv.go index 895563055a5..60b0a7b1a39 100644 --- a/os/genv/genv.go +++ b/os/genv/genv.go @@ -32,7 +32,7 @@ func Map() map[string]string { // Get creates and returns a Var with the value of the environment variable // named by the `key`. It uses the given `def` if the variable does not exist // in the environment. -func Get(key string, def ...interface{}) *gvar.Var { +func Get(key string, def ...any) *gvar.Var { v, ok := os.LookupEnv(key) if !ok { if len(def) > 0 { @@ -87,7 +87,7 @@ func Remove(key ...string) (err error) { // Fetching Rules: // 1. Environment arguments are in uppercase format, eg: GF__; // 2. Command line arguments are in lowercase format, eg: gf..; -func GetWithCmd(key string, def ...interface{}) *gvar.Var { +func GetWithCmd(key string, def ...any) *gvar.Var { envKey := utils.FormatEnvKey(key) if v := os.Getenv(envKey); v != "" { return gvar.New(v) diff --git a/os/gfile/gfile_cache.go b/os/gfile/gfile_cache.go index 731cb1cef6e..ebdbaae241d 100644 --- a/os/gfile/gfile_cache.go +++ b/os/gfile/gfile_cache.go @@ -65,7 +65,7 @@ func GetBytesWithCache(path string, duration ...time.Duration) []byte { if len(duration) > 0 { expire = duration[0] } - r, _ := internalCache.GetOrSetFuncLock(ctx, cacheKey, func(ctx context.Context) (interface{}, error) { + r, _ := internalCache.GetOrSetFuncLock(ctx, cacheKey, func(ctx context.Context) (any, error) { b := GetBytes(path) if b != nil { // Adding this `path` to gfsnotify, diff --git a/os/gfpool/gfpool_file.go b/os/gfpool/gfpool_file.go index 052866d6b70..b77f2fbf485 100644 --- a/os/gfpool/gfpool_file.go +++ b/os/gfpool/gfpool_file.go @@ -31,7 +31,7 @@ func Open(path string, flag int, perm os.FileMode, ttl ...time.Duration) (file * // } pool := pools.GetOrSetFuncLock( fmt.Sprintf("%s&%d&%d&%d", path, flag, fpTTL, perm), - func() interface{} { + func() any { return New(path, flag, perm, fpTTL) }, ).(*Pool) diff --git a/os/gfpool/gfpool_pool.go b/os/gfpool/gfpool_pool.go index 55929b4611c..4bf188e8956 100644 --- a/os/gfpool/gfpool_pool.go +++ b/os/gfpool/gfpool_pool.go @@ -39,7 +39,7 @@ func New(path string, flag int, perm os.FileMode, ttl ...time.Duration) *Pool { // newFilePool creates and returns a file pointer pool with given file path, flag and opening permission. func newFilePool(p *Pool, path string, flag int, perm os.FileMode, ttl time.Duration) *gpool.Pool { - pool := gpool.New(ttl, func() (interface{}, error) { + pool := gpool.New(ttl, func() (any, error) { file, err := os.OpenFile(path, flag, perm) if err != nil { err = gerror.Wrapf(err, `os.OpenFile failed for file "%s", flag "%d", perm "%s"`, path, flag, perm) @@ -53,7 +53,7 @@ func newFilePool(p *Pool, path string, flag int, perm os.FileMode, ttl time.Dura perm: perm, path: path, }, nil - }, func(i interface{}) { + }, func(i any) { _ = i.(*File).File.Close() }) return pool diff --git a/os/gfsnotify/gfsnotify_watcher.go b/os/gfsnotify/gfsnotify_watcher.go index bb24e7465f0..e475aea3c6e 100644 --- a/os/gfsnotify/gfsnotify_watcher.go +++ b/os/gfsnotify/gfsnotify_watcher.go @@ -108,7 +108,7 @@ func (w *Watcher) addWithCallbackFunc( recursive: !watchOption.NoRecursive, } // Register the callback to watcher. - w.callbacks.LockFunc(func(m map[string]interface{}) { + w.callbacks.LockFunc(func(m map[string]any) { list := (*glist.List)(nil) if v, ok := m[path]; !ok { list = glist.New(true) diff --git a/os/gfsnotify/gfsnotify_watcher_loop.go b/os/gfsnotify/gfsnotify_watcher_loop.go index dc12d576389..730931b11d1 100644 --- a/os/gfsnotify/gfsnotify_watcher_loop.go +++ b/os/gfsnotify/gfsnotify_watcher_loop.go @@ -29,7 +29,7 @@ func (w *Watcher) watchLoop() { return } // filter the repeated event in custom duration. - var cacheFunc = func(ctx context.Context) (value interface{}, err error) { + var cacheFunc = func(ctx context.Context) (value any, err error) { w.events.Push(&Event{ event: ev, Path: ev.Name, diff --git a/os/glog/glog.go b/os/glog/glog.go index 9a5a0dd621e..af7e0b293bd 100644 --- a/os/glog/glog.go +++ b/os/glog/glog.go @@ -17,24 +17,24 @@ import ( // ILogger is the API interface for logger. type ILogger interface { - Print(ctx context.Context, v ...interface{}) - Printf(ctx context.Context, format string, v ...interface{}) - Debug(ctx context.Context, v ...interface{}) - Debugf(ctx context.Context, format string, v ...interface{}) - Info(ctx context.Context, v ...interface{}) - Infof(ctx context.Context, format string, v ...interface{}) - Notice(ctx context.Context, v ...interface{}) - Noticef(ctx context.Context, format string, v ...interface{}) - Warning(ctx context.Context, v ...interface{}) - Warningf(ctx context.Context, format string, v ...interface{}) - Error(ctx context.Context, v ...interface{}) - Errorf(ctx context.Context, format string, v ...interface{}) - Critical(ctx context.Context, v ...interface{}) - Criticalf(ctx context.Context, format string, v ...interface{}) - Panic(ctx context.Context, v ...interface{}) - Panicf(ctx context.Context, format string, v ...interface{}) - Fatal(ctx context.Context, v ...interface{}) - Fatalf(ctx context.Context, format string, v ...interface{}) + Print(ctx context.Context, v ...any) + Printf(ctx context.Context, format string, v ...any) + Debug(ctx context.Context, v ...any) + Debugf(ctx context.Context, format string, v ...any) + Info(ctx context.Context, v ...any) + Infof(ctx context.Context, format string, v ...any) + Notice(ctx context.Context, v ...any) + Noticef(ctx context.Context, format string, v ...any) + Warning(ctx context.Context, v ...any) + Warningf(ctx context.Context, format string, v ...any) + Error(ctx context.Context, v ...any) + Errorf(ctx context.Context, format string, v ...any) + Critical(ctx context.Context, v ...any) + Criticalf(ctx context.Context, format string, v ...any) + Panic(ctx context.Context, v ...any) + Panicf(ctx context.Context, format string, v ...any) + Fatal(ctx context.Context, v ...any) + Fatalf(ctx context.Context, format string, v ...any) } const ( diff --git a/os/glog/glog_api.go b/os/glog/glog_api.go index 3529973e8e6..cf9a6e74ab1 100644 --- a/os/glog/glog_api.go +++ b/os/glog/glog_api.go @@ -10,100 +10,100 @@ import "context" // Print prints `v` with newline using fmt.Sprintln. // The parameter `v` can be multiple variables. -func Print(ctx context.Context, v ...interface{}) { +func Print(ctx context.Context, v ...any) { defaultLogger.Print(ctx, v...) } // Printf prints `v` with format `format` using fmt.Sprintf. // The parameter `v` can be multiple variables. -func Printf(ctx context.Context, format string, v ...interface{}) { +func Printf(ctx context.Context, format string, v ...any) { defaultLogger.Printf(ctx, format, v...) } // Fatal prints the logging content with [FATA] header and newline, then exit the current process. -func Fatal(ctx context.Context, v ...interface{}) { +func Fatal(ctx context.Context, v ...any) { defaultLogger.Fatal(ctx, v...) } // Fatalf prints the logging content with [FATA] header, custom format and newline, then exit the current process. -func Fatalf(ctx context.Context, format string, v ...interface{}) { +func Fatalf(ctx context.Context, format string, v ...any) { defaultLogger.Fatalf(ctx, format, v...) } // Panic prints the logging content with [PANI] header and newline, then panics. -func Panic(ctx context.Context, v ...interface{}) { +func Panic(ctx context.Context, v ...any) { defaultLogger.Panic(ctx, v...) } // Panicf prints the logging content with [PANI] header, custom format and newline, then panics. -func Panicf(ctx context.Context, format string, v ...interface{}) { +func Panicf(ctx context.Context, format string, v ...any) { defaultLogger.Panicf(ctx, format, v...) } // Info prints the logging content with [INFO] header and newline. -func Info(ctx context.Context, v ...interface{}) { +func Info(ctx context.Context, v ...any) { defaultLogger.Info(ctx, v...) } // Infof prints the logging content with [INFO] header, custom format and newline. -func Infof(ctx context.Context, format string, v ...interface{}) { +func Infof(ctx context.Context, format string, v ...any) { defaultLogger.Infof(ctx, format, v...) } // Debug prints the logging content with [DEBU] header and newline. -func Debug(ctx context.Context, v ...interface{}) { +func Debug(ctx context.Context, v ...any) { defaultLogger.Debug(ctx, v...) } // Debugf prints the logging content with [DEBU] header, custom format and newline. -func Debugf(ctx context.Context, format string, v ...interface{}) { +func Debugf(ctx context.Context, format string, v ...any) { defaultLogger.Debugf(ctx, format, v...) } // Notice prints the logging content with [NOTI] header and newline. // It also prints caller stack info if stack feature is enabled. -func Notice(ctx context.Context, v ...interface{}) { +func Notice(ctx context.Context, v ...any) { defaultLogger.Notice(ctx, v...) } // Noticef prints the logging content with [NOTI] header, custom format and newline. // It also prints caller stack info if stack feature is enabled. -func Noticef(ctx context.Context, format string, v ...interface{}) { +func Noticef(ctx context.Context, format string, v ...any) { defaultLogger.Noticef(ctx, format, v...) } // Warning prints the logging content with [WARN] header and newline. // It also prints caller stack info if stack feature is enabled. -func Warning(ctx context.Context, v ...interface{}) { +func Warning(ctx context.Context, v ...any) { defaultLogger.Warning(ctx, v...) } // Warningf prints the logging content with [WARN] header, custom format and newline. // It also prints caller stack info if stack feature is enabled. -func Warningf(ctx context.Context, format string, v ...interface{}) { +func Warningf(ctx context.Context, format string, v ...any) { defaultLogger.Warningf(ctx, format, v...) } // Error prints the logging content with [ERRO] header and newline. // It also prints caller stack info if stack feature is enabled. -func Error(ctx context.Context, v ...interface{}) { +func Error(ctx context.Context, v ...any) { defaultLogger.Error(ctx, v...) } // Errorf prints the logging content with [ERRO] header, custom format and newline. // It also prints caller stack info if stack feature is enabled. -func Errorf(ctx context.Context, format string, v ...interface{}) { +func Errorf(ctx context.Context, format string, v ...any) { defaultLogger.Errorf(ctx, format, v...) } // Critical prints the logging content with [CRIT] header and newline. // It also prints caller stack info if stack feature is enabled. -func Critical(ctx context.Context, v ...interface{}) { +func Critical(ctx context.Context, v ...any) { defaultLogger.Critical(ctx, v...) } // Criticalf prints the logging content with [CRIT] header, custom format and newline. // It also prints caller stack info if stack feature is enabled. -func Criticalf(ctx context.Context, format string, v ...interface{}) { +func Criticalf(ctx context.Context, format string, v ...any) { defaultLogger.Criticalf(ctx, format, v...) } diff --git a/os/glog/glog_config.go b/os/glog/glog_config.go index 615caa68e3f..b626db837e1 100644 --- a/os/glog/glog_config.go +++ b/os/glog/glog_config.go @@ -17,7 +17,7 @@ func SetConfig(config Config) error { } // SetConfigWithMap set configurations with map for the defaultLogger. -func SetConfigWithMap(m map[string]interface{}) error { +func SetConfigWithMap(m map[string]any) error { return defaultLogger.SetConfigWithMap(m) } @@ -104,12 +104,12 @@ func GetFlags() int { // from context and printing them to logging content. // // Note that multiple calls of this function will overwrite the previous set context keys. -func SetCtxKeys(keys ...interface{}) { +func SetCtxKeys(keys ...any) { defaultLogger.SetCtxKeys(keys...) } // GetCtxKeys retrieves and returns the context keys for logging. -func GetCtxKeys() []interface{} { +func GetCtxKeys() []any { return defaultLogger.GetCtxKeys() } diff --git a/os/glog/glog_instance.go b/os/glog/glog_instance.go index 3b732606ded..4f6dad14e34 100644 --- a/os/glog/glog_instance.go +++ b/os/glog/glog_instance.go @@ -25,7 +25,7 @@ func Instance(name ...string) *Logger { if len(name) > 0 && name[0] != "" { key = name[0] } - return instances.GetOrSetFuncLock(key, func() interface{} { + return instances.GetOrSetFuncLock(key, func() any { return New() }).(*Logger) } diff --git a/os/glog/glog_logger.go b/os/glog/glog_logger.go index 942986dae97..b64a0ae1177 100644 --- a/os/glog/glog_logger.go +++ b/os/glog/glog_logger.go @@ -194,7 +194,7 @@ func (l *Logger) print(ctx context.Context, level int, stack string, values ...a // Context values. if len(l.config.CtxKeys) > 0 { for _, ctxKey := range l.config.CtxKeys { - var ctxValue interface{} + var ctxValue any if ctxValue = ctx.Value(ctxKey); ctxValue == nil { ctxValue = ctx.Value(gctx.StrKey(gconv.String(ctxKey))) } @@ -355,7 +355,7 @@ func (l *Logger) getFpFromPool(ctx context.Context, path string) *gfpool.File { } // printStd prints content `s` without stack. -func (l *Logger) printStd(ctx context.Context, level int, values ...interface{}) { +func (l *Logger) printStd(ctx context.Context, level int, values ...any) { // nil logger, print nothing if l == nil { return @@ -364,7 +364,7 @@ func (l *Logger) printStd(ctx context.Context, level int, values ...interface{}) } // printErr prints content `s` with stack check. -func (l *Logger) printErr(ctx context.Context, level int, values ...interface{}) { +func (l *Logger) printErr(ctx context.Context, level int, values ...any) { // nil logger, print nothing if l == nil { return @@ -378,7 +378,7 @@ func (l *Logger) printErr(ctx context.Context, level int, values ...interface{}) } // format formats `values` using fmt.Sprintf. -func (l *Logger) format(format string, values ...interface{}) string { +func (l *Logger) format(format string, values ...any) string { return fmt.Sprintf(format, values...) } diff --git a/os/glog/glog_logger_api.go b/os/glog/glog_logger_api.go index 748fae74c7a..b66ee2a32ab 100644 --- a/os/glog/glog_logger_api.go +++ b/os/glog/glog_logger_api.go @@ -14,63 +14,63 @@ import ( // Print prints `v` with newline using fmt.Sprintln. // The parameter `v` can be multiple variables. -func (l *Logger) Print(ctx context.Context, v ...interface{}) { +func (l *Logger) Print(ctx context.Context, v ...any) { l.printStd(ctx, LEVEL_NONE, v...) } // Printf prints `v` with format `format` using fmt.Sprintf. // The parameter `v` can be multiple variables. -func (l *Logger) Printf(ctx context.Context, format string, v ...interface{}) { +func (l *Logger) Printf(ctx context.Context, format string, v ...any) { l.printStd(ctx, LEVEL_NONE, l.format(format, v...)) } // Fatal prints the logging content with [FATA] header and newline, then exit the current process. -func (l *Logger) Fatal(ctx context.Context, v ...interface{}) { +func (l *Logger) Fatal(ctx context.Context, v ...any) { l.printErr(ctx, LEVEL_FATA, v...) os.Exit(1) } // Fatalf prints the logging content with [FATA] header, custom format and newline, then exit the current process. -func (l *Logger) Fatalf(ctx context.Context, format string, v ...interface{}) { +func (l *Logger) Fatalf(ctx context.Context, format string, v ...any) { l.printErr(ctx, LEVEL_FATA, l.format(format, v...)) os.Exit(1) } // Panic prints the logging content with [PANI] header and newline, then panics. -func (l *Logger) Panic(ctx context.Context, v ...interface{}) { +func (l *Logger) Panic(ctx context.Context, v ...any) { l.printErr(ctx, LEVEL_PANI, v...) panic(fmt.Sprint(v...)) } // Panicf prints the logging content with [PANI] header, custom format and newline, then panics. -func (l *Logger) Panicf(ctx context.Context, format string, v ...interface{}) { +func (l *Logger) Panicf(ctx context.Context, format string, v ...any) { l.printErr(ctx, LEVEL_PANI, l.format(format, v...)) panic(l.format(format, v...)) } // Info prints the logging content with [INFO] header and newline. -func (l *Logger) Info(ctx context.Context, v ...interface{}) { +func (l *Logger) Info(ctx context.Context, v ...any) { if l.checkLevel(LEVEL_INFO) { l.printStd(ctx, LEVEL_INFO, v...) } } // Infof prints the logging content with [INFO] header, custom format and newline. -func (l *Logger) Infof(ctx context.Context, format string, v ...interface{}) { +func (l *Logger) Infof(ctx context.Context, format string, v ...any) { if l.checkLevel(LEVEL_INFO) { l.printStd(ctx, LEVEL_INFO, l.format(format, v...)) } } // Debug prints the logging content with [DEBU] header and newline. -func (l *Logger) Debug(ctx context.Context, v ...interface{}) { +func (l *Logger) Debug(ctx context.Context, v ...any) { if l.checkLevel(LEVEL_DEBU) { l.printStd(ctx, LEVEL_DEBU, v...) } } // Debugf prints the logging content with [DEBU] header, custom format and newline. -func (l *Logger) Debugf(ctx context.Context, format string, v ...interface{}) { +func (l *Logger) Debugf(ctx context.Context, format string, v ...any) { if l.checkLevel(LEVEL_DEBU) { l.printStd(ctx, LEVEL_DEBU, l.format(format, v...)) } @@ -78,7 +78,7 @@ func (l *Logger) Debugf(ctx context.Context, format string, v ...interface{}) { // Notice prints the logging content with [NOTI] header and newline. // It also prints caller stack info if stack feature is enabled. -func (l *Logger) Notice(ctx context.Context, v ...interface{}) { +func (l *Logger) Notice(ctx context.Context, v ...any) { if l.checkLevel(LEVEL_NOTI) { l.printStd(ctx, LEVEL_NOTI, v...) } @@ -86,7 +86,7 @@ func (l *Logger) Notice(ctx context.Context, v ...interface{}) { // Noticef prints the logging content with [NOTI] header, custom format and newline. // It also prints caller stack info if stack feature is enabled. -func (l *Logger) Noticef(ctx context.Context, format string, v ...interface{}) { +func (l *Logger) Noticef(ctx context.Context, format string, v ...any) { if l.checkLevel(LEVEL_NOTI) { l.printStd(ctx, LEVEL_NOTI, l.format(format, v...)) } @@ -94,7 +94,7 @@ func (l *Logger) Noticef(ctx context.Context, format string, v ...interface{}) { // Warning prints the logging content with [WARN] header and newline. // It also prints caller stack info if stack feature is enabled. -func (l *Logger) Warning(ctx context.Context, v ...interface{}) { +func (l *Logger) Warning(ctx context.Context, v ...any) { if l.checkLevel(LEVEL_WARN) { l.printStd(ctx, LEVEL_WARN, v...) } @@ -102,7 +102,7 @@ func (l *Logger) Warning(ctx context.Context, v ...interface{}) { // Warningf prints the logging content with [WARN] header, custom format and newline. // It also prints caller stack info if stack feature is enabled. -func (l *Logger) Warningf(ctx context.Context, format string, v ...interface{}) { +func (l *Logger) Warningf(ctx context.Context, format string, v ...any) { if l.checkLevel(LEVEL_WARN) { l.printStd(ctx, LEVEL_WARN, l.format(format, v...)) } @@ -110,7 +110,7 @@ func (l *Logger) Warningf(ctx context.Context, format string, v ...interface{}) // Error prints the logging content with [ERRO] header and newline. // It also prints caller stack info if stack feature is enabled. -func (l *Logger) Error(ctx context.Context, v ...interface{}) { +func (l *Logger) Error(ctx context.Context, v ...any) { if l.checkLevel(LEVEL_ERRO) { l.printErr(ctx, LEVEL_ERRO, v...) } @@ -118,7 +118,7 @@ func (l *Logger) Error(ctx context.Context, v ...interface{}) { // Errorf prints the logging content with [ERRO] header, custom format and newline. // It also prints caller stack info if stack feature is enabled. -func (l *Logger) Errorf(ctx context.Context, format string, v ...interface{}) { +func (l *Logger) Errorf(ctx context.Context, format string, v ...any) { if l.checkLevel(LEVEL_ERRO) { l.printErr(ctx, LEVEL_ERRO, l.format(format, v...)) } @@ -126,7 +126,7 @@ func (l *Logger) Errorf(ctx context.Context, format string, v ...interface{}) { // Critical prints the logging content with [CRIT] header and newline. // It also prints caller stack info if stack feature is enabled. -func (l *Logger) Critical(ctx context.Context, v ...interface{}) { +func (l *Logger) Critical(ctx context.Context, v ...any) { if l.checkLevel(LEVEL_CRIT) { l.printErr(ctx, LEVEL_CRIT, v...) } @@ -134,7 +134,7 @@ func (l *Logger) Critical(ctx context.Context, v ...interface{}) { // Criticalf prints the logging content with [CRIT] header, custom format and newline. // It also prints caller stack info if stack feature is enabled. -func (l *Logger) Criticalf(ctx context.Context, format string, v ...interface{}) { +func (l *Logger) Criticalf(ctx context.Context, format string, v ...any) { if l.checkLevel(LEVEL_CRIT) { l.printErr(ctx, LEVEL_CRIT, l.format(format, v...)) } diff --git a/os/glog/glog_logger_config.go b/os/glog/glog_logger_config.go index fcd83d162bd..ed1a5b0a7f9 100644 --- a/os/glog/glog_logger_config.go +++ b/os/glog/glog_logger_config.go @@ -34,7 +34,7 @@ type Config struct { StSkip int `json:"stSkip"` // Skipping count for stack. StStatus int `json:"stStatus"` // Stack status(1: enabled - default; 0: disabled) StFilter string `json:"stFilter"` // Stack string filter. - CtxKeys []interface{} `json:"ctxKeys"` // Context keys for logging, which is used for value retrieving from context. + CtxKeys []any `json:"ctxKeys"` // Context keys for logging, which is used for value retrieving from context. HeaderPrint bool `json:"header"` // Print header or not(true in default). StdoutPrint bool `json:"stdout"` // Output to stdout or not(true in default). LevelPrint bool `json:"levelPrint"` // Print level format string or not(true in default). @@ -61,7 +61,7 @@ func DefaultConfig() Config { Flags: F_TIME_STD, TimeFormat: defaultTimeFormat, Level: LEVEL_ALL, - CtxKeys: []interface{}{}, + CtxKeys: []any{}, StStatus: 1, HeaderPrint: true, StdoutPrint: true, @@ -101,7 +101,7 @@ func (l *Logger) SetConfig(config Config) error { } // SetConfigWithMap set configurations with map for the logger. -func (l *Logger) SetConfigWithMap(m map[string]interface{}) error { +func (l *Logger) SetConfigWithMap(m map[string]any) error { if len(m) == 0 { return gerror.NewCode(gcode.CodeInvalidParameter, "configuration cannot be empty") } @@ -183,13 +183,13 @@ func (l *Logger) SetStackFilter(filter string) { // from context and printing them to logging content. // // Note that multiple calls of this function will overwrite the previous set context keys. -func (l *Logger) SetCtxKeys(keys ...interface{}) { +func (l *Logger) SetCtxKeys(keys ...any) { l.config.CtxKeys = keys } // AppendCtxKeys appends extra keys to logger. // It ignores the key if it is already appended to the logger previously. -func (l *Logger) AppendCtxKeys(keys ...interface{}) { +func (l *Logger) AppendCtxKeys(keys ...any) { var isExist bool for _, key := range keys { isExist = false @@ -206,7 +206,7 @@ func (l *Logger) AppendCtxKeys(keys ...interface{}) { } // GetCtxKeys retrieves and returns the context keys for logging. -func (l *Logger) GetCtxKeys() []interface{} { +func (l *Logger) GetCtxKeys() []any { return l.config.CtxKeys } diff --git a/os/glog/glog_logger_rotate.go b/os/glog/glog_logger_rotate.go index 7e840361663..9bdf766a64b 100644 --- a/os/glog/glog_logger_rotate.go +++ b/os/glog/glog_logger_rotate.go @@ -235,7 +235,7 @@ func (l *Logger) rotateChecksTimely(ctx context.Context) { // ============================================================= // Backups count limitation and expiration checks. // ============================================================= - backupFiles := garray.NewSortedArray(func(a, b interface{}) int { + backupFiles := garray.NewSortedArray(func(a, b any) int { // Sorted by rotated/backup file mtime. // The older rotated/backup file is put in the head of array. var ( @@ -274,7 +274,7 @@ func (l *Logger) rotateChecksTimely(ctx context.Context) { mtime time.Time subDuration time.Duration ) - backupFiles.Iterator(func(_ int, v interface{}) bool { + backupFiles.Iterator(func(_ int, v any) bool { path := v.(string) mtime = gfile.MTime(path) subDuration = now.Sub(mtime) diff --git a/os/glog/glog_z_unit_config_test.go b/os/glog/glog_z_unit_config_test.go index bb31284d812..520bafec2e8 100644 --- a/os/glog/glog_z_unit_config_test.go +++ b/os/glog/glog_z_unit_config_test.go @@ -17,7 +17,7 @@ import ( func Test_SetConfigWithMap(t *testing.T) { gtest.C(t, func(t *gtest.T) { l := New() - m := map[string]interface{}{ + m := map[string]any{ "path": "/var/log", "level": "all", "stdout": false, @@ -35,7 +35,7 @@ func Test_SetConfigWithMap_LevelStr(t *testing.T) { gtest.C(t, func(t *gtest.T) { buffer := bytes.NewBuffer(nil) l := New() - m := map[string]interface{}{ + m := map[string]any{ "level": "all", } err := l.SetConfigWithMap(m) @@ -52,7 +52,7 @@ func Test_SetConfigWithMap_LevelStr(t *testing.T) { gtest.C(t, func(t *gtest.T) { buffer := bytes.NewBuffer(nil) l := New() - m := map[string]interface{}{ + m := map[string]any{ "level": "warn", } err := l.SetConfigWithMap(m) diff --git a/os/glog/glog_z_unit_test.go b/os/glog/glog_z_unit_test.go index 87a83771391..6d7f9784715 100644 --- a/os/glog/glog_z_unit_test.go +++ b/os/glog/glog_z_unit_test.go @@ -156,7 +156,7 @@ func Test_SetConfigWithMap(t *testing.T) { defaultLog := glog.DefaultLogger().Clone() defer glog.SetDefaultLogger(defaultLog) gtest.C(t, func(t *gtest.T) { - t.Assert(glog.SetConfigWithMap(map[string]interface{}{ + t.Assert(glog.SetConfigWithMap(map[string]any{ "level": "all", }), nil) }) @@ -442,10 +442,10 @@ func Test_Ctx_Config(t *testing.T) { gtest.C(t, func(t *gtest.T) { w := bytes.NewBuffer(nil) l := glog.NewWithWriter(w) - m := map[string]interface{}{ + m := map[string]any{ "CtxKeys": g.SliceStr{"Trace-Id", "Span-Id", "Test"}, } - var nilMap map[string]interface{} + var nilMap map[string]any err := l.SetConfigWithMap(m) t.AssertNil(err) diff --git a/os/gmlock/gmlock_locker.go b/os/gmlock/gmlock_locker.go index b802d76f898..424fcf056a7 100644 --- a/os/gmlock/gmlock_locker.go +++ b/os/gmlock/gmlock_locker.go @@ -128,7 +128,7 @@ func (l *Locker) Clear() { // getOrNewMutex returns the mutex of given `key` if it exists, // or else creates and returns a new one. func (l *Locker) getOrNewMutex(key string) *sync.RWMutex { - return l.m.GetOrSetFuncLock(key, func() interface{} { + return l.m.GetOrSetFuncLock(key, func() any { return &sync.RWMutex{} }).(*sync.RWMutex) } diff --git a/os/gproc/gproc_comm_receive.go b/os/gproc/gproc_comm_receive.go index 942c04e69f9..5271b4d3d3d 100644 --- a/os/gproc/gproc_comm_receive.go +++ b/os/gproc/gproc_comm_receive.go @@ -39,7 +39,7 @@ func Receive(group ...string) *MsgRequest { } else { groupName = defaultGroupNameForProcComm } - queue := commReceiveQueues.GetOrSetFuncLock(groupName, func() interface{} { + queue := commReceiveQueues.GetOrSetFuncLock(groupName, func() any { return gqueue.New(maxLengthForProcMsgQueue) }).(*gqueue.Queue) diff --git a/os/gproc/gproc_manager.go b/os/gproc/gproc_manager.go index 3fafb11ba7a..233d3c84c71 100644 --- a/os/gproc/gproc_manager.go +++ b/os/gproc/gproc_manager.go @@ -61,7 +61,7 @@ func (m *Manager) RemoveProcess(pid int) { // Processes retrieves and returns all processes in current manager. func (m *Manager) Processes() []*Process { processes := make([]*Process, 0) - m.processes.RLockFunc(func(m map[int]interface{}) { + m.processes.RLockFunc(func(m map[int]any) { for _, v := range m { processes = append(processes, v.(*Process)) } diff --git a/os/gres/gres_file.go b/os/gres/gres_file.go index a63269fcf0f..48185f06cef 100644 --- a/os/gres/gres_file.go +++ b/os/gres/gres_file.go @@ -60,7 +60,7 @@ func (f *File) Export(dst string, option ...ExportOption) error { // MarshalJSON implements the interface MarshalJSON for json.Marshal. func (f File) MarshalJSON() ([]byte, error) { info := f.FileInfo() - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "name": f.Name(), "size": info.Size(), "time": info.ModTime(), diff --git a/os/gres/gres_instance.go b/os/gres/gres_instance.go index e04dc431192..7b58c497906 100644 --- a/os/gres/gres_instance.go +++ b/os/gres/gres_instance.go @@ -25,7 +25,7 @@ func Instance(name ...string) *Resource { if len(name) > 0 && name[0] != "" { key = name[0] } - return instances.GetOrSetFuncLock(key, func() interface{} { + return instances.GetOrSetFuncLock(key, func() any { return New() }).(*Resource) } diff --git a/os/gres/gres_resource.go b/os/gres/gres_resource.go index 783758fdb42..cdc5f7b8dd2 100644 --- a/os/gres/gres_resource.go +++ b/os/gres/gres_resource.go @@ -32,7 +32,7 @@ const ( // New creates and returns a new resource object. func New() *Resource { return &Resource{ - tree: gtree.NewBTree(defaultTreeM, func(v1, v2 interface{}) int { + tree: gtree.NewBTree(defaultTreeM, func(v1, v2 any) int { return strings.Compare(v1.(string), v2.(string)) }), } @@ -189,7 +189,7 @@ func (r *Resource) doScanDir(path string, pattern string, recursive bool, onlyFi } // Used for type checking for first entry. first := true - r.tree.IteratorFrom(path, true, func(key, value interface{}) bool { + r.tree.IteratorFrom(path, true, func(key, value any) bool { if first { if !value.(*File).FileInfo().IsDir() { return false @@ -275,7 +275,7 @@ func (r *Resource) Export(src, dst string, option ...ExportOption) error { // Dump prints the files of current resource object. func (r *Resource) Dump() { var info os.FileInfo - r.tree.Iterator(func(key, value interface{}) bool { + r.tree.Iterator(func(key, value any) bool { info = value.(*File).FileInfo() fmt.Printf( "%v %8s %s\n", diff --git a/os/grpool/grpool_pool.go b/os/grpool/grpool_pool.go index a2fc9b14b94..4296fc2c384 100644 --- a/os/grpool/grpool_pool.go +++ b/os/grpool/grpool_pool.go @@ -106,7 +106,7 @@ func (p *Pool) asynchronousWorker() { defer p.count.Add(-1) var ( - listItem interface{} + listItem any poolItem *localPoolItem ) // Harding working, one by one, job never empty, worker never die. diff --git a/os/gsession/gsession_session.go b/os/gsession/gsession_session.go index 1844b51de2b..41d64b7d640 100644 --- a/os/gsession/gsession_session.go +++ b/os/gsession/gsession_session.go @@ -103,7 +103,7 @@ func (s *Session) Close() error { } // Set sets key-value pair to this session. -func (s *Session) Set(key string, value interface{}) (err error) { +func (s *Session) Set(key string, value any) (err error) { if err = s.init(); err != nil { return err } @@ -118,7 +118,7 @@ func (s *Session) Set(key string, value interface{}) (err error) { } // SetMap batch sets the session using map. -func (s *Session) SetMap(data map[string]interface{}) (err error) { +func (s *Session) SetMap(data map[string]any) (err error) { if err = s.init(); err != nil { return err } @@ -204,9 +204,9 @@ func (s *Session) SetIdFunc(f func(ttl time.Duration) string) error { // Data returns all data as map. // Note that it's using value copy internally for concurrent-safe purpose. -func (s *Session) Data() (sessionData map[string]interface{}, err error) { +func (s *Session) Data() (sessionData map[string]any, err error) { if s.id == "" { - return map[string]interface{}{}, nil + return map[string]any{}, nil } if err = s.init(); err != nil { return nil, err @@ -262,7 +262,7 @@ func (s *Session) IsDirty() bool { // Get retrieves session value with given key. // It returns `def` if the key does not exist in the session if `def` is given, // or else it returns nil. -func (s *Session) Get(key string, def ...interface{}) (value *gvar.Var, err error) { +func (s *Session) Get(key string, def ...any) (value *gvar.Var, err error) { if s.id == "" { return nil, nil } @@ -296,7 +296,7 @@ func (s *Session) MustId() string { } // MustGet performs as function Get, but it panics if any error occurs. -func (s *Session) MustGet(key string, def ...interface{}) *gvar.Var { +func (s *Session) MustGet(key string, def ...any) *gvar.Var { v, err := s.Get(key, def...) if err != nil { panic(err) @@ -305,7 +305,7 @@ func (s *Session) MustGet(key string, def ...interface{}) *gvar.Var { } // MustSet performs as function Set, but it panics if any error occurs. -func (s *Session) MustSet(key string, value interface{}) { +func (s *Session) MustSet(key string, value any) { err := s.Set(key, value) if err != nil { panic(err) @@ -313,7 +313,7 @@ func (s *Session) MustSet(key string, value interface{}) { } // MustSetMap performs as function SetMap, but it panics if any error occurs. -func (s *Session) MustSetMap(data map[string]interface{}) { +func (s *Session) MustSetMap(data map[string]any) { err := s.SetMap(data) if err != nil { panic(err) @@ -330,7 +330,7 @@ func (s *Session) MustContains(key string) bool { } // MustData performs as function Data, but it panics if any error occurs. -func (s *Session) MustData() map[string]interface{} { +func (s *Session) MustData() map[string]any { m, err := s.Data() if err != nil { panic(err) diff --git a/os/gsession/gsession_storage.go b/os/gsession/gsession_storage.go index da5d4e791eb..a2e1f141d63 100644 --- a/os/gsession/gsession_storage.go +++ b/os/gsession/gsession_storage.go @@ -21,21 +21,21 @@ type Storage interface { // Get retrieves and returns certain session value with given key. // It returns nil if the key does not exist in the session. - Get(ctx context.Context, sessionId string, key string) (value interface{}, err error) + Get(ctx context.Context, sessionId string, key string) (value any, err error) // GetSize retrieves and returns the size of key-value pairs from storage. GetSize(ctx context.Context, sessionId string) (size int, err error) // Data retrieves all key-value pairs as map from storage. - Data(ctx context.Context, sessionId string) (sessionData map[string]interface{}, err error) + Data(ctx context.Context, sessionId string) (sessionData map[string]any, err error) // Set sets one key-value session pair to the storage. // The parameter `ttl` specifies the TTL for the session id. - Set(ctx context.Context, sessionId string, key string, value interface{}, ttl time.Duration) error + Set(ctx context.Context, sessionId string, key string, value any, ttl time.Duration) error // SetMap batch sets key-value session pairs as map to the storage. // The parameter `ttl` specifies the TTL for the session id. - SetMap(ctx context.Context, sessionId string, mapData map[string]interface{}, ttl time.Duration) error + SetMap(ctx context.Context, sessionId string, mapData map[string]any, ttl time.Duration) error // Remove deletes key-value pair from specified session from storage. Remove(ctx context.Context, sessionId string, key string) error diff --git a/os/gsession/gsession_storage_base.go b/os/gsession/gsession_storage_base.go index 8436f54114f..49a8b4dc8b0 100644 --- a/os/gsession/gsession_storage_base.go +++ b/os/gsession/gsession_storage_base.go @@ -24,12 +24,12 @@ func (s *StorageBase) New(ctx context.Context, ttl time.Duration) (id string, er // Get retrieves certain session value with given key. // It returns nil if the key does not exist in the session. -func (s *StorageBase) Get(ctx context.Context, sessionId string, key string) (value interface{}, err error) { +func (s *StorageBase) Get(ctx context.Context, sessionId string, key string) (value any, err error) { return nil, ErrorDisabled } // Data retrieves all key-value pairs as map from storage. -func (s *StorageBase) Data(ctx context.Context, sessionId string) (sessionData map[string]interface{}, err error) { +func (s *StorageBase) Data(ctx context.Context, sessionId string) (sessionData map[string]any, err error) { return nil, ErrorDisabled } @@ -40,13 +40,13 @@ func (s *StorageBase) GetSize(ctx context.Context, sessionId string) (size int, // Set sets key-value session pair to the storage. // The parameter `ttl` specifies the TTL for the session id (not for the key-value pair). -func (s *StorageBase) Set(ctx context.Context, sessionId string, key string, value interface{}, ttl time.Duration) error { +func (s *StorageBase) Set(ctx context.Context, sessionId string, key string, value any, ttl time.Duration) error { return ErrorDisabled } // SetMap batch sets key-value session pairs with map to the storage. // The parameter `ttl` specifies the TTL for the session id(not for the key-value pair). -func (s *StorageBase) SetMap(ctx context.Context, sessionId string, mapData map[string]interface{}, ttl time.Duration) error { +func (s *StorageBase) SetMap(ctx context.Context, sessionId string, mapData map[string]any, ttl time.Duration) error { return ErrorDisabled } diff --git a/os/gsession/gsession_storage_file.go b/os/gsession/gsession_storage_file.go index 27c83dcd662..41b66dde57d 100644 --- a/os/gsession/gsession_storage_file.go +++ b/os/gsession/gsession_storage_file.go @@ -157,7 +157,7 @@ func (s *StorageFile) GetSession(ctx context.Context, sessionId string, ttl time return nil, err } } - var m map[string]interface{} + var m map[string]any if err = json.UnmarshalUseNumber(content, &m); err != nil { return nil, err } diff --git a/os/gsession/gsession_storage_redis.go b/os/gsession/gsession_storage_redis.go index 34e895e4c26..29ef01ee33c 100644 --- a/os/gsession/gsession_storage_redis.go +++ b/os/gsession/gsession_storage_redis.go @@ -89,7 +89,7 @@ func (s *StorageRedis) GetSession(ctx context.Context, sessionId string, ttl tim if len(content) == 0 { return nil, nil } - var m map[string]interface{} + var m map[string]any if err = json.UnmarshalUseNumber(content, &m); err != nil { return nil, err } diff --git a/os/gsession/gsession_storage_redis_hashtable.go b/os/gsession/gsession_storage_redis_hashtable.go index 71a9ab07a70..070e039fdf5 100644 --- a/os/gsession/gsession_storage_redis_hashtable.go +++ b/os/gsession/gsession_storage_redis_hashtable.go @@ -39,7 +39,7 @@ func NewStorageRedisHashTable(redis *gredis.Redis, prefix ...string) *StorageRed // Get retrieves session value with given key. // It returns nil if the key does not exist in the session. -func (s *StorageRedisHashTable) Get(ctx context.Context, sessionId string, key string) (value interface{}, err error) { +func (s *StorageRedisHashTable) Get(ctx context.Context, sessionId string, key string) (value any, err error) { v, err := s.redis.HGet(ctx, s.sessionIdToRedisKey(sessionId), key) if err != nil { return nil, err @@ -51,7 +51,7 @@ func (s *StorageRedisHashTable) Get(ctx context.Context, sessionId string, key s } // Data retrieves all key-value pairs as map from storage. -func (s *StorageRedisHashTable) Data(ctx context.Context, sessionId string) (data map[string]interface{}, err error) { +func (s *StorageRedisHashTable) Data(ctx context.Context, sessionId string) (data map[string]any, err error) { m, err := s.redis.HGetAll(ctx, s.sessionIdToRedisKey(sessionId)) if err != nil { return nil, err @@ -67,8 +67,8 @@ func (s *StorageRedisHashTable) GetSize(ctx context.Context, sessionId string) ( // Set sets key-value session pair to the storage. // The parameter `ttl` specifies the TTL for the session id (not for the key-value pair). -func (s *StorageRedisHashTable) Set(ctx context.Context, sessionId string, key string, value interface{}, ttl time.Duration) error { - _, err := s.redis.HSet(ctx, s.sessionIdToRedisKey(sessionId), map[string]interface{}{ +func (s *StorageRedisHashTable) Set(ctx context.Context, sessionId string, key string, value any, ttl time.Duration) error { + _, err := s.redis.HSet(ctx, s.sessionIdToRedisKey(sessionId), map[string]any{ key: value, }) return err @@ -76,7 +76,7 @@ func (s *StorageRedisHashTable) Set(ctx context.Context, sessionId string, key s // SetMap batch sets key-value session pairs with map to the storage. // The parameter `ttl` specifies the TTL for the session id(not for the key-value pair). -func (s *StorageRedisHashTable) SetMap(ctx context.Context, sessionId string, data map[string]interface{}, ttl time.Duration) error { +func (s *StorageRedisHashTable) SetMap(ctx context.Context, sessionId string, data map[string]any, ttl time.Duration) error { err := s.redis.HMSet(ctx, s.sessionIdToRedisKey(sessionId), data) return err } diff --git a/os/gsession/gsession_z_example_test.go b/os/gsession/gsession_z_example_test.go index 869c778b82b..dba90870797 100644 --- a/os/gsession/gsession_z_example_test.go +++ b/os/gsession/gsession_z_example_test.go @@ -65,7 +65,7 @@ func ExampleSession_SetMap() { storage := gsession.NewStorageFile("", time.Second) manager := gsession.New(time.Second, storage) s := manager.New(gctx.New()) - fmt.Println(s.SetMap(map[string]interface{}{}) == nil) + fmt.Println(s.SetMap(map[string]any{}) == nil) // Output: // true diff --git a/os/gspath/gspath.go b/os/gspath/gspath.go index 12fdbe70c88..0ccced9f718 100644 --- a/os/gspath/gspath.go +++ b/os/gspath/gspath.go @@ -67,7 +67,7 @@ func Get(root string, cache bool) *SPath { if root == "" { root = "/" } - return pathsMap.GetOrSetFuncLock(root, func() interface{} { + return pathsMap.GetOrSetFuncLock(root, func() any { return New(root, cache) }).(*SPath) } diff --git a/os/gstructs/gstructs.go b/os/gstructs/gstructs.go index b0ac1550cc5..1d926ca761f 100644 --- a/os/gstructs/gstructs.go +++ b/os/gstructs/gstructs.go @@ -210,7 +210,7 @@ func FieldMap(in FieldMapInput) (map[string]Field, error) { func StructType(object any) (*Type, error) { // if already reflect.Type if reflectType, ok := object.(reflect.Type); ok { - for reflectType.Kind() == reflect.Ptr { + for reflectType.Kind() == reflect.Pointer { reflectType = reflectType.Elem() } if reflectType.Kind() == reflect.Struct { @@ -233,7 +233,7 @@ func StructType(object any) (*Type, error) { reflectKind = reflectValue.Kind() for { switch reflectKind { - case reflect.Ptr: + case reflect.Pointer: if !reflectValue.IsValid() || reflectValue.IsNil() { // If pointer is type of *struct and nil, then automatically create a temporary struct. reflectValue = reflect.New(reflectValue.Type().Elem()).Elem() diff --git a/os/gstructs/gstructs_field.go b/os/gstructs/gstructs_field.go index 5fc234242f3..bbbed2e0043 100644 --- a/os/gstructs/gstructs_field.go +++ b/os/gstructs/gstructs_field.go @@ -86,7 +86,7 @@ func (f *Field) OriginalKind() reflect.Kind { reflectType = f.Value.Type() reflectKind = reflectType.Kind() ) - for reflectKind == reflect.Ptr { + for reflectKind == reflect.Pointer { reflectType = reflectType.Elem() reflectKind = reflectType.Kind() } @@ -102,7 +102,7 @@ func (f *Field) OriginalValue() reflect.Value { reflectKind = reflectType.Kind() ) - for reflectKind == reflect.Ptr && !f.IsNil() { + for reflectKind == reflect.Pointer && !f.IsNil() { reflectValue = reflectValue.Elem() reflectKind = reflectValue.Type().Kind() } diff --git a/os/gstructs/gstructs_tag.go b/os/gstructs/gstructs_tag.go index 701ac7ec3f0..1bb65cc5636 100644 --- a/os/gstructs/gstructs_tag.go +++ b/os/gstructs/gstructs_tag.go @@ -76,7 +76,7 @@ func ParseTag(tag string) map[string]string { // Note that, // 1. It only retrieves the exported attributes with first letter upper-case from struct. // 2. The parameter `priority` should be given, it only retrieves fields that has given tag. -func TagFields(pointer interface{}, priority []string) ([]Field, error) { +func TagFields(pointer any, priority []string) ([]Field, error) { return getFieldValuesByTagPriority(pointer, priority, map[string]struct{}{}) } @@ -88,7 +88,7 @@ func TagFields(pointer interface{}, priority []string) ([]Field, error) { // 1. It only retrieves the exported attributes with first letter upper-case from struct. // 2. The parameter `priority` should be given, it only retrieves fields that has given tag. // 3. If one field has no specified tag, it uses its field name as result map key. -func TagMapName(pointer interface{}, priority []string) (map[string]string, error) { +func TagMapName(pointer any, priority []string) (map[string]string, error) { fields, err := TagFields(pointer, priority) if err != nil { return nil, err @@ -107,7 +107,7 @@ func TagMapName(pointer interface{}, priority []string) (map[string]string, erro // 1. It only retrieves the exported attributes with first letter upper-case from struct. // 2. The parameter `priority` should be given, it only retrieves fields that has given tag. // 3. If one field has no specified tag, it uses its field name as result map key. -func TagMapField(object interface{}, priority []string) (map[string]Field, error) { +func TagMapField(object any, priority []string) (map[string]Field, error) { fields, err := TagFields(object, priority) if err != nil { return nil, err @@ -120,7 +120,7 @@ func TagMapField(object interface{}, priority []string) (map[string]Field, error return tagMap, nil } -func getFieldValues(structObject interface{}) ([]Field, error) { +func getFieldValues(structObject any) ([]Field, error) { var ( reflectValue reflect.Value reflectKind reflect.Kind @@ -134,7 +134,7 @@ func getFieldValues(structObject interface{}) ([]Field, error) { } for { switch reflectKind { - case reflect.Ptr: + case reflect.Pointer: if !reflectValue.IsValid() || reflectValue.IsNil() { // If pointer is type of *struct and nil, then automatically create a temporary struct. reflectValue = reflect.New(reflectValue.Type().Elem()).Elem() @@ -152,7 +152,7 @@ func getFieldValues(structObject interface{}) ([]Field, error) { } exitLoop: - for reflectKind == reflect.Ptr { + for reflectKind == reflect.Pointer { reflectValue = reflectValue.Elem() reflectKind = reflectValue.Kind() } @@ -177,7 +177,7 @@ exitLoop: } func getFieldValuesByTagPriority( - pointer interface{}, priority []string, repeatedTagFilteringMap map[string]struct{}, + pointer any, priority []string, repeatedTagFilteringMap map[string]struct{}, ) ([]Field, error) { fields, err := getFieldValues(pointer) if err != nil { diff --git a/os/gtime/gtime_sql.go b/os/gtime/gtime_sql.go index 4fdd4902b12..7104a3e04d3 100644 --- a/os/gtime/gtime_sql.go +++ b/os/gtime/gtime_sql.go @@ -6,7 +6,7 @@ import ( // Scan implements interface used by Scan in package database/sql for Scanning value // from database to local golang variable. -func (t *Time) Scan(value interface{}) error { +func (t *Time) Scan(value any) error { if t == nil { return nil } diff --git a/os/gtime/gtime_time.go b/os/gtime/gtime_time.go index 06a7e0db2be..9766446340c 100644 --- a/os/gtime/gtime_time.go +++ b/os/gtime/gtime_time.go @@ -31,7 +31,7 @@ type iUnixNano interface { // New("2024-10-29") // New(1390876568) // New(t) // The t is type of time.Time. -func New(param ...interface{}) *Time { +func New(param ...any) *Time { if len(param) > 0 { switch r := param[0].(type) { case time.Time: @@ -553,7 +553,7 @@ func (t *Time) UnmarshalText(data []byte) error { func (t *Time) NoValidation() {} // DeepCopy implements interface for deep copy of current type. -func (t *Time) DeepCopy() interface{} { +func (t *Time) DeepCopy() any { if t == nil { return nil } diff --git a/os/gtimer/gtimer_queue.go b/os/gtimer/gtimer_queue.go index 92b5752319c..0c09df3eb56 100644 --- a/os/gtimer/gtimer_queue.go +++ b/os/gtimer/gtimer_queue.go @@ -31,7 +31,7 @@ type priorityQueueHeap struct { // priorityQueueItem stores the queue item which has a `priority` attribute to sort itself in heap. type priorityQueueItem struct { - value interface{} + value any priority int64 } @@ -53,7 +53,7 @@ func (q *priorityQueue) NextPriority() int64 { // Push pushes a value to the queue. // The `priority` specifies the priority of the value. // The lesser the `priority` value the higher priority of the `value`. -func (q *priorityQueue) Push(value interface{}, priority int64) { +func (q *priorityQueue) Push(value any, priority int64) { q.mu.Lock() defer q.mu.Unlock() heap.Push(q.heap, priorityQueueItem{ @@ -69,7 +69,7 @@ func (q *priorityQueue) Push(value interface{}, priority int64) { } // Pop retrieves, removes and returns the most high priority value from the queue. -func (q *priorityQueue) Pop() interface{} { +func (q *priorityQueue) Pop() any { q.mu.Lock() defer q.mu.Unlock() if v := heap.Pop(q.heap); v != nil { diff --git a/os/gtimer/gtimer_queue_heap.go b/os/gtimer/gtimer_queue_heap.go index c4b2f5dbe3a..96741831857 100644 --- a/os/gtimer/gtimer_queue_heap.go +++ b/os/gtimer/gtimer_queue_heap.go @@ -26,12 +26,12 @@ func (h *priorityQueueHeap) Swap(i, j int) { } // Push pushes an item to the heap. -func (h *priorityQueueHeap) Push(x interface{}) { +func (h *priorityQueueHeap) Push(x any) { h.array = append(h.array, x.(priorityQueueItem)) } // Pop retrieves, removes and returns the most high priority item from the heap. -func (h *priorityQueueHeap) Pop() interface{} { +func (h *priorityQueueHeap) Pop() any { length := len(h.array) if length == 0 { return nil diff --git a/os/gtimer/gtimer_timer_loop.go b/os/gtimer/gtimer_timer_loop.go index 7fbdf04afa7..0803662330d 100644 --- a/os/gtimer/gtimer_timer_loop.go +++ b/os/gtimer/gtimer_timer_loop.go @@ -39,7 +39,7 @@ func (t *Timer) loop() { // proceed function proceeds the timer job checking and running logic. func (t *Timer) proceed(currentTimerTicks int64) { - var value interface{} + var value any for { value = t.queue.Pop() if value == nil { diff --git a/os/gview/gview_buildin.go b/os/gview/gview_buildin.go index 0ddb63804da..cbd21cf8ee2 100644 --- a/os/gview/gview_buildin.go +++ b/os/gview/gview_buildin.go @@ -24,7 +24,7 @@ import ( ) // buildInFuncDump implements build-in template function: dump -func (view *View) buildInFuncDump(values ...interface{}) string { +func (view *View) buildInFuncDump(values ...any) string { buffer := bytes.NewBuffer(nil) buffer.WriteString("\n") buffer.WriteString("