change 'interface{}' to 'any' (#108)

This commit is contained in:
Neil O'Toole 2022-12-16 16:34:33 -07:00 committed by GitHub
parent a419e0b693
commit e674cdc724
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
60 changed files with 500 additions and 500 deletions

View File

@ -86,7 +86,7 @@ func TestCreateTblTestBytes(t *testing.T) {
) )
fBytes := proj.ReadFile(fixt.GopherPath) fBytes := proj.ReadFile(fixt.GopherPath)
data := []interface{}{fixt.GopherFilename, fBytes} data := []any{fixt.GopherFilename, fBytes}
require.Equal(t, int64(1), th.CreateTable(true, src, tblDef, data)) require.Equal(t, int64(1), th.CreateTable(true, src, tblDef, data))
} }
@ -115,7 +115,7 @@ func TestOutputRaw(t *testing.T) {
th, src, _, _ := testh.NewWith(t, handle) th, src, _, _ := testh.NewWith(t, handle)
// Create the table and insert data // Create the table and insert data
insertRow := []interface{}{fixt.GopherFilename, wantBytes} insertRow := []any{fixt.GopherFilename, wantBytes}
require.Equal(t, int64(1), th.CreateTable(true, src, tblDef, insertRow)) require.Equal(t, int64(1), th.CreateTable(true, src, tblDef, insertRow))
// 1. Query and check that libsq is returning bytes correctly. // 1. Query and check that libsq is returning bytes correctly.

View File

@ -98,7 +98,7 @@ func TestRecordWriterAdapter_FlushAfterN(t *testing.T) {
// Write some records // Write some records
for i := 0; i < writeRecCount; i++ { for i := 0; i < writeRecCount; i++ {
recCh <- []interface{}{1} recCh <- []any{1}
} }
close(recCh) close(recCh)
@ -151,7 +151,7 @@ func TestRecordWriterAdapter_FlushAfterDuration(t *testing.T) {
// Write some records // Write some records
for i := 0; i < writeRecCount; i++ { for i := 0; i < writeRecCount; i++ {
recCh <- []interface{}{1} recCh <- []any{1}
time.Sleep(sleepTime) time.Sleep(sleepTime)
} }
close(recCh) close(recCh)

View File

@ -19,19 +19,19 @@ import (
type monoEncoder struct { type monoEncoder struct {
} }
func (e monoEncoder) encodeTime(b []byte, v interface{}) ([]byte, error) { func (e monoEncoder) encodeTime(b []byte, v any) ([]byte, error) {
return e.doEncodeTime(b, v, stringz.TimeFormat) return e.doEncodeTime(b, v, stringz.TimeFormat)
} }
func (e monoEncoder) encodeDatetime(b []byte, v interface{}) ([]byte, error) { func (e monoEncoder) encodeDatetime(b []byte, v any) ([]byte, error) {
return e.doEncodeTime(b, v, stringz.DatetimeFormat) return e.doEncodeTime(b, v, stringz.DatetimeFormat)
} }
func (e monoEncoder) encodeDate(b []byte, v interface{}) ([]byte, error) { func (e monoEncoder) encodeDate(b []byte, v any) ([]byte, error) {
return e.doEncodeTime(b, v, stringz.DateFormat) return e.doEncodeTime(b, v, stringz.DateFormat)
} }
func (e monoEncoder) doEncodeTime(b []byte, v interface{}, layout string) ([]byte, error) { func (e monoEncoder) doEncodeTime(b []byte, v any, layout string) ([]byte, error) {
switch v := v.(type) { switch v := v.(type) {
case nil: case nil:
return append(b, "null"...), nil return append(b, "null"...), nil
@ -48,7 +48,7 @@ func (e monoEncoder) doEncodeTime(b []byte, v interface{}, layout string) ([]byt
} }
} }
func (e monoEncoder) encodeAny(b []byte, v interface{}) ([]byte, error) { func (e monoEncoder) encodeAny(b []byte, v any) ([]byte, error) {
switch v := v.(type) { switch v := v.(type) {
default: default:
return b, errz.Errorf("unexpected record field type %T: %#v", v, v) return b, errz.Errorf("unexpected record field type %T: %#v", v, v)
@ -95,19 +95,19 @@ type colorEncoder struct {
clrs internal.Colors clrs internal.Colors
} }
func (e *colorEncoder) encodeTime(b []byte, v interface{}) ([]byte, error) { func (e *colorEncoder) encodeTime(b []byte, v any) ([]byte, error) {
return e.doEncodeTime(b, v, stringz.TimeFormat) return e.doEncodeTime(b, v, stringz.TimeFormat)
} }
func (e *colorEncoder) encodeDatetime(b []byte, v interface{}) ([]byte, error) { func (e *colorEncoder) encodeDatetime(b []byte, v any) ([]byte, error) {
return e.doEncodeTime(b, v, stringz.DatetimeFormat) return e.doEncodeTime(b, v, stringz.DatetimeFormat)
} }
func (e *colorEncoder) encodeDate(b []byte, v interface{}) ([]byte, error) { func (e *colorEncoder) encodeDate(b []byte, v any) ([]byte, error) {
return e.doEncodeTime(b, v, stringz.DateFormat) return e.doEncodeTime(b, v, stringz.DateFormat)
} }
func (e *colorEncoder) doEncodeTime(b []byte, v interface{}, layout string) ([]byte, error) { func (e *colorEncoder) doEncodeTime(b []byte, v any, layout string) ([]byte, error) {
start := len(b) start := len(b)
switch v := v.(type) { switch v := v.(type) {
@ -135,7 +135,7 @@ func (e *colorEncoder) doEncodeTime(b []byte, v interface{}, layout string) ([]b
} }
} }
func (e *colorEncoder) encodeAny(b []byte, v interface{}) ([]byte, error) { func (e *colorEncoder) encodeAny(b []byte, v any) ([]byte, error) {
switch v := v.(type) { switch v := v.(type) {
default: default:
return b, errz.Errorf("unexpected record field type %T: %#v", v, v) return b, errz.Errorf("unexpected record field type %T: %#v", v, v)
@ -225,8 +225,8 @@ func newPunc(fm *output.Formatting) punc {
return p return p
} }
func getFieldEncoders(recMeta sqlz.RecordMeta, fm *output.Formatting) []func(b []byte, v interface{}) ([]byte, error) { func getFieldEncoders(recMeta sqlz.RecordMeta, fm *output.Formatting) []func(b []byte, v any) ([]byte, error) {
encodeFns := make([]func(b []byte, v interface{}) ([]byte, error), len(recMeta)) encodeFns := make([]func(b []byte, v any) ([]byte, error), len(recMeta))
if fm.IsMonochrome() { if fm.IsMonochrome() {
enc := monoEncoder{} enc := monoEncoder{}

View File

@ -16,7 +16,7 @@ import (
// Encoder encapsulates the methods of a JSON encoder. // Encoder encapsulates the methods of a JSON encoder.
type Encoder interface { type Encoder interface {
Encode(v interface{}) error Encode(v any) error
SetEscapeHTML(on bool) SetEscapeHTML(on bool)
SetIndent(prefix, indent string) SetIndent(prefix, indent string)
} }
@ -29,22 +29,22 @@ func TestEncode(t *testing.T) {
pretty bool pretty bool
color bool color bool
sortMap bool sortMap bool
v interface{} v any
want string want string
}{ }{
{name: "nil", pretty: true, v: nil, want: "null\n"}, {name: "nil", pretty: true, v: nil, want: "null\n"},
{name: "slice_empty", pretty: true, v: []int{}, want: "[]\n"}, {name: "slice_empty", pretty: true, v: []int{}, want: "[]\n"},
{name: "slice_1_pretty", pretty: true, v: []interface{}{1}, want: "[\n 1\n]\n"}, {name: "slice_1_pretty", pretty: true, v: []any{1}, want: "[\n 1\n]\n"},
{name: "slice_1_no_pretty", v: []interface{}{1}, want: "[1]\n"}, {name: "slice_1_no_pretty", v: []any{1}, want: "[1]\n"},
{name: "slice_2_pretty", pretty: true, v: []interface{}{1, true}, want: "[\n 1,\n true\n]\n"}, {name: "slice_2_pretty", pretty: true, v: []any{1, true}, want: "[\n 1,\n true\n]\n"},
{name: "slice_2_no_pretty", v: []interface{}{1, true}, want: "[1,true]\n"}, {name: "slice_2_no_pretty", v: []any{1, true}, want: "[1,true]\n"},
{name: "map_int_empty", pretty: true, v: map[string]int{}, want: "{}\n"}, {name: "map_int_empty", pretty: true, v: map[string]int{}, want: "{}\n"},
{name: "map_interface_empty", pretty: true, v: map[string]interface{}{}, want: "{}\n"}, {name: "map_interface_empty", pretty: true, v: map[string]any{}, want: "{}\n"},
{name: "map_interface_empty_sorted", pretty: true, sortMap: true, v: map[string]interface{}{}, want: "{}\n"}, {name: "map_interface_empty_sorted", pretty: true, sortMap: true, v: map[string]any{}, want: "{}\n"},
{name: "map_1_pretty", pretty: true, sortMap: true, v: map[string]interface{}{"one": 1}, want: "{\n \"one\": 1\n}\n"}, {name: "map_1_pretty", pretty: true, sortMap: true, v: map[string]any{"one": 1}, want: "{\n \"one\": 1\n}\n"},
{name: "map_1_no_pretty", sortMap: true, v: map[string]interface{}{"one": 1}, want: "{\"one\":1}\n"}, {name: "map_1_no_pretty", sortMap: true, v: map[string]any{"one": 1}, want: "{\"one\":1}\n"},
{name: "map_2_pretty", pretty: true, sortMap: true, v: map[string]interface{}{"one": 1, "two": 2}, want: "{\n \"one\": 1,\n \"two\": 2\n}\n"}, {name: "map_2_pretty", pretty: true, sortMap: true, v: map[string]any{"one": 1, "two": 2}, want: "{\n \"one\": 1,\n \"two\": 2\n}\n"},
{name: "map_2_no_pretty", sortMap: true, v: map[string]interface{}{"one": 1, "two": 2}, want: "{\"one\":1,\"two\":2}\n"}, {name: "map_2_no_pretty", sortMap: true, v: map[string]any{"one": 1, "two": 2}, want: "{\"one\":1,\"two\":2}\n"},
{name: "tinystruct", pretty: true, v: TinyStruct{FBool: true}, want: "{\n \"f_bool\": true\n}\n"}, {name: "tinystruct", pretty: true, v: TinyStruct{FBool: true}, want: "{\n \"f_bool\": true\n}\n"},
} }
@ -78,14 +78,14 @@ func TestEncode_Slice(t *testing.T) {
name string name string
pretty bool pretty bool
color bool color bool
v []interface{} v []any
want string want string
}{ }{
{name: "nil", pretty: true, v: nil, want: "null\n"}, {name: "nil", pretty: true, v: nil, want: "null\n"},
{name: "empty", pretty: true, v: []interface{}{}, want: "[]\n"}, {name: "empty", pretty: true, v: []any{}, want: "[]\n"},
{name: "one", pretty: true, v: []interface{}{1}, want: "[\n 1\n]\n"}, {name: "one", pretty: true, v: []any{1}, want: "[\n 1\n]\n"},
{name: "two", pretty: true, v: []interface{}{1, true}, want: "[\n 1,\n true\n]\n"}, {name: "two", pretty: true, v: []any{1, true}, want: "[\n 1,\n true\n]\n"},
{name: "three", pretty: true, v: []interface{}{1, true, "hello"}, want: "[\n 1,\n true,\n \"hello\"\n]\n"}, {name: "three", pretty: true, v: []any{1, true, "hello"}, want: "[\n 1,\n true,\n \"hello\"\n]\n"},
} }
for _, tc := range testCases { for _, tc := range testCases {
@ -114,8 +114,8 @@ func TestEncode_Slice(t *testing.T) {
func TestEncode_SmallStruct(t *testing.T) { func TestEncode_SmallStruct(t *testing.T) {
v := SmallStruct{ v := SmallStruct{
FInt: 7, FInt: 7,
FSlice: []interface{}{64, true}, FSlice: []any{64, true},
FMap: map[string]interface{}{ FMap: map[string]any{
"m_float64": 64.64, "m_float64": 64.64,
"m_string": "hello", "m_string": "hello",
}, },
@ -158,13 +158,13 @@ func TestEncode_SmallStruct(t *testing.T) {
} }
func TestEncode_Map_Nested(t *testing.T) { func TestEncode_Map_Nested(t *testing.T) {
v := map[string]interface{}{ v := map[string]any{
"m_bool1": true, "m_bool1": true,
"m_nest1": map[string]interface{}{ "m_nest1": map[string]any{
"m_nest1_bool": true, "m_nest1_bool": true,
"m_nest2": map[string]interface{}{ "m_nest2": map[string]any{
"m_nest2_bool": true, "m_nest2_bool": true,
"m_nest3": map[string]interface{}{ "m_nest3": map[string]any{
"m_nest3_bool": true, "m_nest3_bool": true,
}, },
}, },
@ -207,9 +207,9 @@ func TestEncode_Map_Nested(t *testing.T) {
} }
// TestEncode_Map_StringNotInterface tests maps with a string key // TestEncode_Map_StringNotInterface tests maps with a string key
// but the value type is not interface{}. // but the value type is not any.
// For example, map[string]bool. This test is necessary because the // For example, map[string]bool. This test is necessary because the
// encoder has a fast path for map[string]interface{} // encoder has a fast path for map[string]any
func TestEncode_Map_StringNotInterface(t *testing.T) { func TestEncode_Map_StringNotInterface(t *testing.T) {
testCases := []struct { testCases := []struct {
pretty bool pretty bool
@ -264,7 +264,7 @@ func TestEncode_RawMessage(t *testing.T) {
name string name string
pretty bool pretty bool
color bool color bool
v interface{} v any
want string want string
}{ }{
{name: "empty", pretty: false, v: jcolorenc.RawMessage(`{}`), want: "{}\n"}, {name: "empty", pretty: false, v: jcolorenc.RawMessage(`{}`), want: "{}\n"},
@ -300,7 +300,7 @@ func TestEncode_RawMessage(t *testing.T) {
// TestEncode_Map_StringNotInterface tests map[string]json.RawMessage. // TestEncode_Map_StringNotInterface tests map[string]json.RawMessage.
// This test is necessary because the encoder has a fast path // This test is necessary because the encoder has a fast path
// for map[string]interface{} // for map[string]any
func TestEncode_Map_StringRawMessage(t *testing.T) { func TestEncode_Map_StringRawMessage(t *testing.T) {
raw := jcolorenc.RawMessage(`{"one":1,"two":2}`) raw := jcolorenc.RawMessage(`{"one":1,"two":2}`)
@ -383,7 +383,7 @@ func TestEncode_BigStruct(t *testing.T) {
} }
// TestEncode_Map_Not_StringInterface tests map encoding where // TestEncode_Map_Not_StringInterface tests map encoding where
// the map is not map[string]interface{} (for which the encoder // the map is not map[string]any (for which the encoder
// has a fast path). // has a fast path).
// //
// NOTE: Currently the encoder is broken wrt colors enabled // NOTE: Currently the encoder is broken wrt colors enabled
@ -431,19 +431,19 @@ type BigStruct struct {
FFloat64 float64 `json:"f_float64"` FFloat64 float64 `json:"f_float64"`
FBool bool `json:"f_bool"` FBool bool `json:"f_bool"`
FBytes []byte `json:"f_bytes"` FBytes []byte `json:"f_bytes"`
FNil interface{} `json:"f_nil"` FNil any `json:"f_nil"`
FString string `json:"f_string"` FString string `json:"f_string"`
FMap map[string]interface{} `json:"f_map"` FMap map[string]any `json:"f_map"`
FSmallStruct SmallStruct `json:"f_smallstruct"` FSmallStruct SmallStruct `json:"f_smallstruct"`
FInterface interface{} `json:"f_interface"` FInterface any `json:"f_interface"`
FInterfaces []interface{} `json:"f_interfaces"` FInterfaces []any `json:"f_interfaces"`
} }
// SmallStruct is a small test struct. // SmallStruct is a small test struct.
type SmallStruct struct { type SmallStruct struct {
FInt int `json:"f_int"` FInt int `json:"f_int"`
FSlice []interface{} `json:"f_slice"` FSlice []any `json:"f_slice"`
FMap map[string]interface{} `json:"f_map"` FMap map[string]any `json:"f_map"`
FTinyStruct TinyStruct `json:"f_tinystruct"` FTinyStruct TinyStruct `json:"f_tinystruct"`
FString string `json:"f_string"` FString string `json:"f_string"`
} }
@ -471,7 +471,7 @@ func newBigStruct() BigStruct {
FBytes: []byte("hello"), FBytes: []byte("hello"),
FNil: nil, FNil: nil,
FString: "hello", FString: "hello",
FMap: map[string]interface{}{ FMap: map[string]any{
"m_int64": int64(64), "m_int64": int64(64),
"m_string": "hello", "m_string": "hello",
"m_bool": true, "m_bool": true,
@ -479,16 +479,16 @@ func newBigStruct() BigStruct {
"m_smallstruct": newSmallStruct(), "m_smallstruct": newSmallStruct(),
}, },
FSmallStruct: newSmallStruct(), FSmallStruct: newSmallStruct(),
FInterface: interface{}("hello"), FInterface: any("hello"),
FInterfaces: []interface{}{int64(64), "hello", true}, FInterfaces: []any{int64(64), "hello", true},
} }
} }
func newSmallStruct() SmallStruct { func newSmallStruct() SmallStruct {
return SmallStruct{ return SmallStruct{
FInt: 7, FInt: 7,
FSlice: []interface{}{64, true}, FSlice: []any{64, true},
FMap: map[string]interface{}{ FMap: map[string]any{
"m_float64": 64.64, "m_float64": 64.64,
"m_string": "hello", "m_string": "hello",
}, },

View File

@ -957,7 +957,7 @@ func init() {
} }
} }
func syntaxError(b []byte, msg string, args ...interface{}) error { func syntaxError(b []byte, msg string, args ...any) error {
e := new(SyntaxError) e := new(SyntaxError)
i := syntaxErrorMsgOffset i := syntaxErrorMsgOffset
if i != ^uintptr(0) { if i != ^uintptr(0) {
@ -1049,11 +1049,11 @@ var (
timePtrType = reflect.PtrTo(timeType) timePtrType = reflect.PtrTo(timeType)
rawMessagePtrType = reflect.PtrTo(rawMessageType) rawMessagePtrType = reflect.PtrTo(rawMessageType)
sliceInterfaceType = reflect.TypeOf(([]interface{})(nil)) sliceInterfaceType = reflect.TypeOf(([]any)(nil))
mapStringInterfaceType = reflect.TypeOf((map[string]interface{})(nil)) mapStringInterfaceType = reflect.TypeOf((map[string]any)(nil))
mapStringRawMessageType = reflect.TypeOf((map[string]RawMessage)(nil)) mapStringRawMessageType = reflect.TypeOf((map[string]RawMessage)(nil))
interfaceType = reflect.TypeOf((*interface{})(nil)).Elem() interfaceType = reflect.TypeOf((*any)(nil)).Elem()
jsonMarshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() jsonMarshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
jsonUnmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() jsonUnmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()

View File

@ -737,15 +737,15 @@ func (d decoder) decodeMapStringInterface(b []byte, p unsafe.Pointer) ([]byte, e
} }
i := 0 i := 0
m := *(*map[string]interface{})(p) m := *(*map[string]any)(p)
if m == nil { if m == nil {
m = make(map[string]interface{}, 64) m = make(map[string]any, 64)
} }
var err error var err error
var key string var key string
var val interface{} var val any
var input = b var input = b
b = b[1:] b = b[1:]
@ -1009,8 +1009,8 @@ func (d decoder) decodePointer(b []byte, p unsafe.Pointer, t reflect.Type, decod
} }
func (d decoder) decodeInterface(b []byte, p unsafe.Pointer) ([]byte, error) { func (d decoder) decodeInterface(b []byte, p unsafe.Pointer) ([]byte, error) {
val := *(*interface{})(p) val := *(*any)(p)
*(*interface{})(p) = nil *(*any)(p) = nil
if t := reflect.TypeOf(val); t != nil && t.Kind() == reflect.Ptr { if t := reflect.TypeOf(val); t != nil && t.Kind() == reflect.Ptr {
if v := reflect.ValueOf(val); v.IsNil() || t.Elem().Kind() != reflect.Ptr { if v := reflect.ValueOf(val); v.IsNil() || t.Elem().Kind() != reflect.Ptr {
@ -1018,14 +1018,14 @@ func (d decoder) decodeInterface(b []byte, p unsafe.Pointer) ([]byte, error) {
// `null`, and the encoding/json package always nils the destination // `null`, and the encoding/json package always nils the destination
// interface value in this case. // interface value in this case.
if hasNullPrefix(b) { if hasNullPrefix(b) {
*(*interface{})(p) = nil *(*any)(p) = nil
return b[4:], nil return b[4:], nil
} }
} }
b, err := Parse(b, val, d.flags) b, err := Parse(b, val, d.flags)
if err == nil { if err == nil {
*(*interface{})(p) = val *(*any)(p) = val
} }
return b, err return b, err
} }
@ -1037,12 +1037,12 @@ func (d decoder) decodeInterface(b []byte, p unsafe.Pointer) ([]byte, error) {
switch v[0] { switch v[0] {
case '{': case '{':
m := make(map[string]interface{}) m := make(map[string]any)
v, err = d.decodeMapStringInterface(v, unsafe.Pointer(&m)) v, err = d.decodeMapStringInterface(v, unsafe.Pointer(&m))
val = m val = m
case '[': case '[':
a := make([]interface{}, 0, 10) a := make([]any, 0, 10)
v, err = d.decodeSlice(v, unsafe.Pointer(&a), unsafe.Sizeof(a[0]), sliceInterfaceType, decoder.decodeInterface) v, err = d.decodeSlice(v, unsafe.Pointer(&a), unsafe.Sizeof(a[0]), sliceInterfaceType, decoder.decodeInterface)
val = a val = a
@ -1083,13 +1083,13 @@ func (d decoder) decodeInterface(b []byte, p unsafe.Pointer) ([]byte, error) {
return b, syntaxError(v, "unexpected trailing trailing tokens after json value") return b, syntaxError(v, "unexpected trailing trailing tokens after json value")
} }
*(*interface{})(p) = val *(*any)(p) = val
return b, nil return b, nil
} }
func (d decoder) decodeMaybeEmptyInterface(b []byte, p unsafe.Pointer, t reflect.Type) ([]byte, error) { func (d decoder) decodeMaybeEmptyInterface(b []byte, p unsafe.Pointer, t reflect.Type) ([]byte, error) {
if hasNullPrefix(b) { if hasNullPrefix(b) {
*(*interface{})(p) = nil *(*any)(p) = nil
return b[4:], nil return b[4:], nil
} }
@ -1098,7 +1098,7 @@ func (d decoder) decodeMaybeEmptyInterface(b []byte, p unsafe.Pointer, t reflect
return Parse(b, e.Interface(), d.flags) return Parse(b, e.Interface(), d.flags)
} }
} else if t.NumMethod() == 0 { // empty interface } else if t.NumMethod() == 0 { // empty interface
return Parse(b, (*interface{})(p), d.flags) return Parse(b, (*any)(p), d.flags)
} }
return d.decodeUnmarshalTypeError(b, p, t) return d.decodeUnmarshalTypeError(b, p, t)

View File

@ -412,7 +412,7 @@ func (e encoder) encodeMap(b []byte, p unsafe.Pointer, t reflect.Type, encodeKey
type element struct { type element struct {
key string key string
val interface{} val any
raw RawMessage raw RawMessage
} }
@ -425,11 +425,11 @@ func (m *mapslice) Less(i, j int) bool { return m.elements[i].key < m.elements[j
func (m *mapslice) Swap(i, j int) { m.elements[i], m.elements[j] = m.elements[j], m.elements[i] } func (m *mapslice) Swap(i, j int) { m.elements[i], m.elements[j] = m.elements[j], m.elements[i] }
var mapslicePool = sync.Pool{ var mapslicePool = sync.Pool{
New: func() interface{} { return new(mapslice) }, New: func() any { return new(mapslice) },
} }
func (e encoder) encodeMapStringInterface(b []byte, p unsafe.Pointer) ([]byte, error) { func (e encoder) encodeMapStringInterface(b []byte, p unsafe.Pointer) ([]byte, error) {
m := *(*map[string]interface{})(p) m := *(*map[string]any)(p)
if m == nil { if m == nil {
return e.clrs.AppendNull(b), nil return e.clrs.AppendNull(b), nil
} }
@ -719,7 +719,7 @@ func (e encoder) encodePointer(b []byte, p unsafe.Pointer, t reflect.Type, encod
} }
func (e encoder) encodeInterface(b []byte, p unsafe.Pointer) ([]byte, error) { func (e encoder) encodeInterface(b []byte, p unsafe.Pointer) ([]byte, error) {
return Append(b, *(*interface{})(p), e.flags, e.clrs, e.indenter) return Append(b, *(*any)(p), e.flags, e.clrs, e.indenter)
} }
func (e encoder) encodeMaybeEmptyInterface(b []byte, p unsafe.Pointer, t reflect.Type) ([]byte, error) { func (e encoder) encodeMaybeEmptyInterface(b []byte, p unsafe.Pointer, t reflect.Type) ([]byte, error) {

View File

@ -191,7 +191,7 @@ func BenchmarkDecoderStream(b *testing.B) {
var buf bytes.Buffer var buf bytes.Buffer
dec := NewDecoder(&buf) dec := NewDecoder(&buf)
buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n") buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n")
var x interface{} var x any
if err := dec.Decode(&x); err != nil { if err := dec.Decode(&x); err != nil {
b.Fatal("Decode:", err) b.Fatal("Decode:", err)
} }

View File

@ -31,7 +31,7 @@ type U struct {
} }
type V struct { type V struct {
F1 interface{} F1 any
F2 int32 F2 int32
F3 Number F3 Number
F4 *VOuter F4 *VOuter
@ -62,18 +62,18 @@ func (*SS) UnmarshalJSON(data []byte) error {
// ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and
// without UseNumber // without UseNumber
var ifaceNumAsFloat64 = map[string]interface{}{ var ifaceNumAsFloat64 = map[string]any{
"k1": float64(1), "k1": float64(1),
"k2": "s", "k2": "s",
"k3": []interface{}{float64(1), float64(2.0), float64(3e-3)}, "k3": []any{float64(1), float64(2.0), float64(3e-3)},
"k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)}, "k4": map[string]any{"kk1": "s", "kk2": float64(2)},
} }
var ifaceNumAsNumber = map[string]interface{}{ var ifaceNumAsNumber = map[string]any{
"k1": Number("1"), "k1": Number("1"),
"k2": "s", "k2": "s",
"k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")}, "k3": []any{Number("1"), Number("2.0"), Number("3e-3")},
"k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")}, "k4": map[string]any{"kk1": "s", "kk2": Number("2")},
} }
type tx struct { type tx struct {
@ -270,9 +270,9 @@ type Ambig struct {
} }
type XYZ struct { type XYZ struct {
X interface{} X any
Y interface{} Y any
Z interface{} Z any
} }
type unexportedWithMethods struct{} type unexportedWithMethods struct{}
@ -400,8 +400,8 @@ type mapStringToStringData struct {
type unmarshalTest struct { type unmarshalTest struct {
in string in string
ptr interface{} ptr any
out interface{} out any
err error err error
useNumber bool useNumber bool
golden bool golden bool
@ -420,14 +420,14 @@ var unmarshalTests = []unmarshalTest{
{in: `-5`, ptr: new(int16), out: int16(-5)}, {in: `-5`, ptr: new(int16), out: int16(-5)},
{in: `2`, ptr: new(Number), out: Number("2"), useNumber: true}, {in: `2`, ptr: new(Number), out: Number("2"), useNumber: true},
{in: `2`, ptr: new(Number), out: Number("2")}, {in: `2`, ptr: new(Number), out: Number("2")},
{in: `2`, ptr: new(interface{}), out: float64(2.0)}, {in: `2`, ptr: new(any), out: float64(2.0)},
{in: `2`, ptr: new(interface{}), out: Number("2"), useNumber: true}, {in: `2`, ptr: new(any), out: Number("2"), useNumber: true},
{in: `"a\u1234"`, ptr: new(string), out: "a\u1234"}, {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"},
{in: `"http:\/\/"`, ptr: new(string), out: "http://"}, {in: `"http:\/\/"`, ptr: new(string), out: "http://"},
{in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"}, {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"},
//TODO //TODO
//{in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"}, //{in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"},
{in: "null", ptr: new(interface{}), out: nil}, {in: "null", ptr: new(any), out: nil},
{in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf(""), 7, "T", "X"}}, {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf(""), 7, "T", "X"}},
{in: `{"X": 23}`, ptr: new(T), out: T{}, err: &UnmarshalTypeError{"number", reflect.TypeOf(""), 8, "T", "X"}}, {in: `{"x": 1}`, ptr: new(tx), out: tx{}}, {in: `{"X": 23}`, ptr: new(T), out: T{}, err: &UnmarshalTypeError{"number", reflect.TypeOf(""), 8, "T", "X"}}, {in: `{"x": 1}`, ptr: new(tx), out: tx{}},
{in: `{"x": 1}`, ptr: new(tx), out: tx{}}, {in: `{"x": 1}`, ptr: new(tx), out: tx{}},
@ -435,8 +435,8 @@ var unmarshalTests = []unmarshalTest{
{in: `{"S": 23}`, ptr: new(W), out: W{}, err: &UnmarshalTypeError{"number", reflect.TypeOf(SS("")), 0, "W", "S"}}, {in: `{"S": 23}`, ptr: new(W), out: W{}, err: &UnmarshalTypeError{"number", reflect.TypeOf(SS("")), 0, "W", "S"}},
{in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}}, {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}},
{in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true}, {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true},
{in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64}, {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsFloat64},
{in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true}, {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(any), out: ifaceNumAsNumber, useNumber: true},
// raw values with whitespace // raw values with whitespace
{in: "\n true ", ptr: new(bool), out: true}, {in: "\n true ", ptr: new(bool), out: true},
@ -478,10 +478,10 @@ var unmarshalTests = []unmarshalTest{
{in: `[1, 2, 3]`, ptr: new(MustNotUnmarshalJSON), err: errors.New("MustNotUnmarshalJSON was used")}, {in: `[1, 2, 3]`, ptr: new(MustNotUnmarshalJSON), err: errors.New("MustNotUnmarshalJSON was used")},
// empty array to interface test // empty array to interface test
{in: `[]`, ptr: new([]interface{}), out: []interface{}{}}, {in: `[]`, ptr: new([]any), out: []any{}},
{in: `null`, ptr: new([]interface{}), out: []interface{}(nil)}, {in: `null`, ptr: new([]any), out: []any(nil)},
{in: `{"T":[]}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": []interface{}{}}}, {in: `{"T":[]}`, ptr: new(map[string]any), out: map[string]any{"T": []any{}}},
{in: `{"T":null}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": interface{}(nil)}}, {in: `{"T":null}`, ptr: new(map[string]any), out: map[string]any{"T": any(nil)}},
// composite tests // composite tests
{in: allValueIndent, ptr: new(All), out: allValue}, {in: allValueIndent, ptr: new(All), out: allValue},
@ -1131,7 +1131,7 @@ func TestUnmarshal(t *testing.T) {
func TestUnmarshalMarshal(t *testing.T) { func TestUnmarshalMarshal(t *testing.T) {
initBig() initBig()
var v interface{} var v any
if err := Unmarshal(jsonBig, &v); err != nil { if err := Unmarshal(jsonBig, &v); err != nil {
t.Fatalf("Unmarshal: %v", err) t.Fatalf("Unmarshal: %v", err)
} }
@ -1203,7 +1203,7 @@ type Xint struct {
func TestUnmarshalInterface(t *testing.T) { func TestUnmarshalInterface(t *testing.T) {
var xint Xint var xint Xint
var i interface{} = &xint var i any = &xint
if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil { if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil {
t.Fatalf("Unmarshal: %v", err) t.Fatalf("Unmarshal: %v", err)
} }
@ -1334,8 +1334,8 @@ type All struct {
PSmall *Small PSmall *Small
PPSmall **Small PPSmall **Small
Interface interface{} Interface any
PInterface *interface{} PInterface *any
unexported int unexported int
} }
@ -1669,9 +1669,9 @@ func intpp(x *int) **int {
} }
var interfaceSetTests = []struct { var interfaceSetTests = []struct {
pre interface{} pre any
json string json string
post interface{} post any
}{ }{
{"foo", `"bar"`, "bar"}, {"foo", `"bar"`, "bar"},
{"foo", `2`, 2.0}, {"foo", `2`, 2.0},
@ -1690,7 +1690,7 @@ var interfaceSetTests = []struct {
func TestInterfaceSet(t *testing.T) { func TestInterfaceSet(t *testing.T) {
for _, tt := range interfaceSetTests { for _, tt := range interfaceSetTests {
b := struct{ X interface{} }{tt.pre} b := struct{ X any }{tt.pre}
blob := `{"X":` + tt.json + `}` blob := `{"X":` + tt.json + `}`
if err := Unmarshal([]byte(blob), &b); err != nil { if err := Unmarshal([]byte(blob), &b); err != nil {
t.Errorf("Unmarshal %#q: %v", blob, err) t.Errorf("Unmarshal %#q: %v", blob, err)
@ -1720,7 +1720,7 @@ type NullTest struct {
PBool *bool PBool *bool
Map map[string]string Map map[string]string
Slice []string Slice []string
Interface interface{} Interface any
PRaw *RawMessage PRaw *RawMessage
PTime *time.Time PTime *time.Time
@ -1755,7 +1755,7 @@ type NullTestStrings struct {
PBool *bool `json:",string"` PBool *bool `json:",string"`
Map map[string]string `json:",string"` Map map[string]string `json:",string"`
Slice []string `json:",string"` Slice []string `json:",string"`
Interface interface{} `json:",string"` Interface any `json:",string"`
PRaw *RawMessage `json:",string"` PRaw *RawMessage `json:",string"`
PTime *time.Time `json:",string"` PTime *time.Time `json:",string"`
@ -1976,7 +1976,7 @@ func TestSliceOfCustomByte(t *testing.T) {
} }
var decodeTypeErrorTests = []struct { var decodeTypeErrorTests = []struct {
dest interface{} dest any
src string src string
}{ }{
{new(string), `{"user": "name"}`}, // issue 4628. {new(string), `{"user": "name"}`}, // issue 4628.
@ -2009,7 +2009,7 @@ var unmarshalSyntaxTests = []string{
} }
func TestUnmarshalSyntax(t *testing.T) { func TestUnmarshalSyntax(t *testing.T) {
var x interface{} var x any
for _, src := range unmarshalSyntaxTests { for _, src := range unmarshalSyntaxTests {
err := Unmarshal([]byte(src), &x) err := Unmarshal([]byte(src), &x)
if _, ok := err.(*SyntaxError); !ok { if _, ok := err.(*SyntaxError); !ok {
@ -2022,8 +2022,8 @@ func TestUnmarshalSyntax(t *testing.T) {
// Issue 4660 // Issue 4660
type unexportedFields struct { type unexportedFields struct {
Name string Name string
m map[string]interface{} `json:"-"` m map[string]any `json:"-"`
m2 map[string]interface{} `json:"abcd"` m2 map[string]any `json:"abcd"`
s []int `json:"-"` s []int `json:"-"`
} }
@ -2074,7 +2074,7 @@ func TestUnmarshalJSONLiteralError(t *testing.T) {
// Issue 3717 // Issue 3717
func TestSkipArrayObjects(t *testing.T) { func TestSkipArrayObjects(t *testing.T) {
json := `[{}]` json := `[{}]`
var dest [0]interface{} var dest [0]any
err := Unmarshal([]byte(json), &dest) err := Unmarshal([]byte(json), &dest)
if err != nil { if err != nil {
@ -2085,13 +2085,13 @@ func TestSkipArrayObjects(t *testing.T) {
// Test semantics of AppendPre-filled struct fields and AppendPre-filled map fields. // Test semantics of AppendPre-filled struct fields and AppendPre-filled map fields.
// Issue 4900. // Issue 4900.
func TestPrefilled(t *testing.T) { func TestPrefilled(t *testing.T) {
ptrToMap := func(m map[string]interface{}) *map[string]interface{} { return &m } ptrToMap := func(m map[string]any) *map[string]any { return &m }
// Values here change, cannot reuse table across runs. // Values here change, cannot reuse table across runs.
var prefillTests = []struct { var prefillTests = []struct {
in string in string
ptr interface{} ptr any
out interface{} out any
}{ }{
{ {
in: `{"X": 1, "Y": 2}`, in: `{"X": 1, "Y": 2}`,
@ -2100,8 +2100,8 @@ func TestPrefilled(t *testing.T) {
}, },
{ {
in: `{"X": 1, "Y": 2}`, in: `{"X": 1, "Y": 2}`,
ptr: ptrToMap(map[string]interface{}{"X": float32(3), "Y": int16(4), "Z": 1.5}), ptr: ptrToMap(map[string]any{"X": float32(3), "Y": int16(4), "Z": 1.5}),
out: ptrToMap(map[string]interface{}{"X": float64(1), "Y": float64(2), "Z": 1.5}), out: ptrToMap(map[string]any{"X": float64(1), "Y": float64(2), "Z": 1.5}),
}, },
} }
@ -2118,7 +2118,7 @@ func TestPrefilled(t *testing.T) {
} }
var invalidUnmarshalTests = []struct { var invalidUnmarshalTests = []struct {
v interface{} v any
want string want string
}{ }{
{nil, "json: Unmarshal(nil)"}, {nil, "json: Unmarshal(nil)"},
@ -2141,7 +2141,7 @@ func TestInvalidUnmarshal(t *testing.T) {
} }
var invalidUnmarshalTextTests = []struct { var invalidUnmarshalTextTests = []struct {
v interface{} v any
want string want string
}{ }{
{nil, "json: Unmarshal(nil)"}, {nil, "json: Unmarshal(nil)"},
@ -2173,7 +2173,7 @@ func TestInvalidStringOption(t *testing.T) {
M map[string]string `json:",string"` M map[string]string `json:",string"`
S []string `json:",string"` S []string `json:",string"`
A [1]string `json:",string"` A [1]string `json:",string"`
I interface{} `json:",string"` I any `json:",string"`
P *int `json:",string"` P *int `json:",string"`
}{M: make(map[string]string), S: make([]string, 0), I: num, P: &num} }{M: make(map[string]string), S: make([]string, 0), I: num, P: &num}
@ -2244,8 +2244,8 @@ func TestUnmarshalEmbeddedUnexported(t *testing.T) {
tests := []struct { tests := []struct {
in string in string
ptr interface{} ptr any
out interface{} out any
err error err error
}{{ }{{
// Error since we cannot set S1.embed1, but still able to set S1.R. // Error since we cannot set S1.embed1, but still able to set S1.R.
@ -2336,7 +2336,7 @@ func TestUnmarshalPanic(t *testing.T) {
// The decoder used to hang if decoding into an interface pointing to its own address. // The decoder used to hang if decoding into an interface pointing to its own address.
// See golang.org/issues/31740. // See golang.org/issues/31740.
func TestUnmarshalRecursivePointer(t *testing.T) { func TestUnmarshalRecursivePointer(t *testing.T) {
var v interface{} var v any
v = &v v = &v
data := []byte(`{"a": "b"}`) data := []byte(`{"a": "b"}`)

View File

@ -27,8 +27,8 @@ type Optionals struct {
Slr []string `json:"slr,random"` Slr []string `json:"slr,random"`
Slo []string `json:"slo,omitempty"` Slo []string `json:"slo,omitempty"`
Mr map[string]interface{} `json:"mr"` Mr map[string]any `json:"mr"`
Mo map[string]interface{} `json:",omitempty"` Mo map[string]any `json:",omitempty"`
Fr float64 `json:"fr"` Fr float64 `json:"fr"`
Fo float64 `json:"fo,omitempty"` Fo float64 `json:"fo,omitempty"`
@ -58,8 +58,8 @@ var optionalsExpected = `{
func TestOmitEmpty(t *testing.T) { func TestOmitEmpty(t *testing.T) {
var o Optionals var o Optionals
o.Sw = "something" o.Sw = "something"
o.Mr = map[string]interface{}{} o.Mr = map[string]any{}
o.Mo = map[string]interface{}{} o.Mo = map[string]any{}
got, err := MarshalIndent(&o, "", " ") got, err := MarshalIndent(&o, "", " ")
if err != nil { if err != nil {
@ -134,7 +134,7 @@ func TestEncodeRenamedByteSlice(t *testing.T) {
} }
} }
var unsupportedValues = []interface{}{ var unsupportedValues = []any{
math.NaN(), math.NaN(),
math.Inf(-1), math.Inf(-1),
math.Inf(1), math.Inf(1),
@ -259,14 +259,14 @@ func TestMarshalerEscaping(t *testing.T) {
func TestAnonymousFields(t *testing.T) { func TestAnonymousFields(t *testing.T) {
tests := []struct { tests := []struct {
label string // Test name label string // Test name
makeInput func() interface{} // Function to create input value makeInput func() any // Function to create input value
want string // Expected JSON output want string // Expected JSON output
}{{ }{{
// Both S1 and S2 have a field named X. From the perspective of S, // Both S1 and S2 have a field named X. From the perspective of S,
// it is ambiguous which one X refers to. // it is ambiguous which one X refers to.
// This should not serialize either field. // This should not serialize either field.
label: "AmbiguousField", label: "AmbiguousField",
makeInput: func() interface{} { makeInput: func() any {
type ( type (
S1 struct{ x, X int } S1 struct{ x, X int }
S2 struct{ x, X int } S2 struct{ x, X int }
@ -282,7 +282,7 @@ func TestAnonymousFields(t *testing.T) {
label: "DominantField", label: "DominantField",
// Both S1 and S2 have a field named X, but since S has an X field as // Both S1 and S2 have a field named X, but since S has an X field as
// well, it takes precedence over S1.X and S2.X. // well, it takes precedence over S1.X and S2.X.
makeInput: func() interface{} { makeInput: func() any {
type ( type (
S1 struct{ x, X int } S1 struct{ x, X int }
S2 struct{ x, X int } S2 struct{ x, X int }
@ -298,7 +298,7 @@ func TestAnonymousFields(t *testing.T) {
}, { }, {
// Unexported embedded field of non-struct type should not be serialized. // Unexported embedded field of non-struct type should not be serialized.
label: "UnexportedEmbeddedInt", label: "UnexportedEmbeddedInt",
makeInput: func() interface{} { makeInput: func() any {
type ( type (
myInt int myInt int
S struct{ myInt } S struct{ myInt }
@ -309,7 +309,7 @@ func TestAnonymousFields(t *testing.T) {
}, { }, {
// Exported embedded field of non-struct type should be serialized. // Exported embedded field of non-struct type should be serialized.
label: "ExportedEmbeddedInt", label: "ExportedEmbeddedInt",
makeInput: func() interface{} { makeInput: func() any {
type ( type (
MyInt int MyInt int
S struct{ MyInt } S struct{ MyInt }
@ -321,7 +321,7 @@ func TestAnonymousFields(t *testing.T) {
// Unexported embedded field of pointer to non-struct type // Unexported embedded field of pointer to non-struct type
// should not be serialized. // should not be serialized.
label: "UnexportedEmbeddedIntPointer", label: "UnexportedEmbeddedIntPointer",
makeInput: func() interface{} { makeInput: func() any {
type ( type (
myInt int myInt int
S struct{ *myInt } S struct{ *myInt }
@ -335,7 +335,7 @@ func TestAnonymousFields(t *testing.T) {
// Exported embedded field of pointer to non-struct type // Exported embedded field of pointer to non-struct type
// should be serialized. // should be serialized.
label: "ExportedEmbeddedIntPointer", label: "ExportedEmbeddedIntPointer",
makeInput: func() interface{} { makeInput: func() any {
type ( type (
MyInt int MyInt int
S struct{ *MyInt } S struct{ *MyInt }
@ -350,7 +350,7 @@ func TestAnonymousFields(t *testing.T) {
// exported fields be serialized regardless of whether the struct types // exported fields be serialized regardless of whether the struct types
// themselves are exported. // themselves are exported.
label: "EmbeddedStruct", label: "EmbeddedStruct",
makeInput: func() interface{} { makeInput: func() any {
type ( type (
s1 struct{ x, X int } s1 struct{ x, X int }
S2 struct{ y, Y int } S2 struct{ y, Y int }
@ -367,7 +367,7 @@ func TestAnonymousFields(t *testing.T) {
// exported fields be serialized regardless of whether the struct types // exported fields be serialized regardless of whether the struct types
// themselves are exported. // themselves are exported.
label: "EmbeddedStructPointer", label: "EmbeddedStructPointer",
makeInput: func() interface{} { makeInput: func() any {
type ( type (
s1 struct{ x, X int } s1 struct{ x, X int }
S2 struct{ y, Y int } S2 struct{ y, Y int }
@ -383,7 +383,7 @@ func TestAnonymousFields(t *testing.T) {
// Exported fields on embedded unexported structs at multiple levels // Exported fields on embedded unexported structs at multiple levels
// of nesting should still be serialized. // of nesting should still be serialized.
label: "NestedStructAndInts", label: "NestedStructAndInts",
makeInput: func() interface{} { makeInput: func() any {
type ( type (
MyInt1 int MyInt1 int
MyInt2 int MyInt2 int
@ -411,7 +411,7 @@ func TestAnonymousFields(t *testing.T) {
// the embedded fields behind it. Not properly doing so may // the embedded fields behind it. Not properly doing so may
// result in the wrong output or reflect panics. // result in the wrong output or reflect panics.
label: "EmbeddedFieldBehindNilPointer", label: "EmbeddedFieldBehindNilPointer",
makeInput: func() interface{} { makeInput: func() any {
type ( type (
S2 struct{ Field string } S2 struct{ Field string }
S struct{ *S2 } S struct{ *S2 }
@ -469,19 +469,19 @@ func (nm *nilMarshaler) MarshalJSON() ([]byte, error) {
// Issue 16042. // Issue 16042.
func TestNilMarshal(t *testing.T) { func TestNilMarshal(t *testing.T) {
testCases := []struct { testCases := []struct {
v interface{} v any
want string want string
}{ }{
{v: nil, want: `null`}, {v: nil, want: `null`},
{v: new(float64), want: `0`}, {v: new(float64), want: `0`},
{v: []interface{}(nil), want: `null`}, {v: []any(nil), want: `null`},
{v: []string(nil), want: `null`}, {v: []string(nil), want: `null`},
{v: map[string]string(nil), want: `null`}, {v: map[string]string(nil), want: `null`},
{v: []byte(nil), want: `null`}, {v: []byte(nil), want: `null`},
{v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`}, {v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`},
{v: struct{ M Marshaler }{}, want: `{"M":null}`}, {v: struct{ M Marshaler }{}, want: `{"M":null}`},
{v: struct{ M Marshaler }{(*nilMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, {v: struct{ M Marshaler }{(*nilMarshaler)(nil)}, want: `{"M":"0zenil0"}`},
{v: struct{ M interface{} }{(*nilMarshaler)(nil)}, want: `{"M":null}`}, {v: struct{ M any }{(*nilMarshaler)(nil)}, want: `{"M":null}`},
} }
for _, tt := range testCases { for _, tt := range testCases {
@ -741,7 +741,7 @@ type textint int
func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) } func (i textint) MarshalText() ([]byte, error) { return tenc(`TI:%d`, i) }
func tenc(format string, a ...interface{}) ([]byte, error) { func tenc(format string, a ...any) ([]byte, error) {
var buf bytes.Buffer var buf bytes.Buffer
fmt.Fprintf(&buf, format, a...) fmt.Fprintf(&buf, format, a...)
return buf.Bytes(), nil return buf.Bytes(), nil
@ -750,7 +750,7 @@ func tenc(format string, a ...interface{}) ([]byte, error) {
// Issue 13783 // Issue 13783
func TestEncodeBytekind(t *testing.T) { func TestEncodeBytekind(t *testing.T) {
testdata := []struct { testdata := []struct {
data interface{} data any
want string want string
}{ }{
{byte(7), "7"}, {byte(7), "7"},
@ -823,7 +823,7 @@ func TestMarshalFloat(t *testing.T) {
t.Parallel() t.Parallel()
nfail := 0 nfail := 0
test := func(f float64, bits int) { test := func(f float64, bits int) {
vf := interface{}(f) vf := any(f)
if bits == 32 { if bits == 32 {
f = float64(float32(f)) // round f = float64(float32(f)) // round
vf = float32(f) vf = float32(f)
@ -919,25 +919,25 @@ func TestMarshalRawMessageValue(t *testing.T) {
) )
tests := []struct { tests := []struct {
in interface{} in any
want string want string
ok bool ok bool
}{ }{
// Test with nil RawMessage. // Test with nil RawMessage.
{rawNil, "null", true}, {rawNil, "null", true},
{&rawNil, "null", true}, {&rawNil, "null", true},
{[]interface{}{rawNil}, "[null]", true}, {[]any{rawNil}, "[null]", true},
{&[]interface{}{rawNil}, "[null]", true}, {&[]any{rawNil}, "[null]", true},
{[]interface{}{&rawNil}, "[null]", true}, {[]any{&rawNil}, "[null]", true},
{&[]interface{}{&rawNil}, "[null]", true}, {&[]any{&rawNil}, "[null]", true},
{struct{ M RawMessage }{rawNil}, `{"M":null}`, true}, {struct{ M RawMessage }{rawNil}, `{"M":null}`, true},
{&struct{ M RawMessage }{rawNil}, `{"M":null}`, true}, {&struct{ M RawMessage }{rawNil}, `{"M":null}`, true},
{struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true}, {struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true},
{&struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true}, {&struct{ M *RawMessage }{&rawNil}, `{"M":null}`, true},
{map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, {map[string]any{"M": rawNil}, `{"M":null}`, true},
{&map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, {&map[string]any{"M": rawNil}, `{"M":null}`, true},
{map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, {map[string]any{"M": &rawNil}, `{"M":null}`, true},
{&map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, {&map[string]any{"M": &rawNil}, `{"M":null}`, true},
{T1{rawNil}, "{}", true}, {T1{rawNil}, "{}", true},
{T2{&rawNil}, `{"M":null}`, true}, {T2{&rawNil}, `{"M":null}`, true},
{&T1{rawNil}, "{}", true}, {&T1{rawNil}, "{}", true},
@ -946,18 +946,18 @@ func TestMarshalRawMessageValue(t *testing.T) {
// Test with empty, but non-nil, RawMessage. // Test with empty, but non-nil, RawMessage.
{rawEmpty, "", false}, {rawEmpty, "", false},
{&rawEmpty, "", false}, {&rawEmpty, "", false},
{[]interface{}{rawEmpty}, "", false}, {[]any{rawEmpty}, "", false},
{&[]interface{}{rawEmpty}, "", false}, {&[]any{rawEmpty}, "", false},
{[]interface{}{&rawEmpty}, "", false}, {[]any{&rawEmpty}, "", false},
{&[]interface{}{&rawEmpty}, "", false}, {&[]any{&rawEmpty}, "", false},
{struct{ X RawMessage }{rawEmpty}, "", false}, {struct{ X RawMessage }{rawEmpty}, "", false},
{&struct{ X RawMessage }{rawEmpty}, "", false}, {&struct{ X RawMessage }{rawEmpty}, "", false},
{struct{ X *RawMessage }{&rawEmpty}, "", false}, {struct{ X *RawMessage }{&rawEmpty}, "", false},
{&struct{ X *RawMessage }{&rawEmpty}, "", false}, {&struct{ X *RawMessage }{&rawEmpty}, "", false},
{map[string]interface{}{"nil": rawEmpty}, "", false}, {map[string]any{"nil": rawEmpty}, "", false},
{&map[string]interface{}{"nil": rawEmpty}, "", false}, {&map[string]any{"nil": rawEmpty}, "", false},
{map[string]interface{}{"nil": &rawEmpty}, "", false}, {map[string]any{"nil": &rawEmpty}, "", false},
{&map[string]interface{}{"nil": &rawEmpty}, "", false}, {&map[string]any{"nil": &rawEmpty}, "", false},
{T1{rawEmpty}, "{}", true}, {T1{rawEmpty}, "{}", true},
{T2{&rawEmpty}, "", false}, {T2{&rawEmpty}, "", false},
{&T1{rawEmpty}, "{}", true}, {&T1{rawEmpty}, "{}", true},
@ -970,18 +970,18 @@ func TestMarshalRawMessageValue(t *testing.T) {
// See https://golang.org/issues/14493#issuecomment-255857318 // See https://golang.org/issues/14493#issuecomment-255857318
{rawText, `"foo"`, true}, // Issue6458 {rawText, `"foo"`, true}, // Issue6458
{&rawText, `"foo"`, true}, {&rawText, `"foo"`, true},
{[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 {[]any{rawText}, `["foo"]`, true}, // Issue6458
{&[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 {&[]any{rawText}, `["foo"]`, true}, // Issue6458
{[]interface{}{&rawText}, `["foo"]`, true}, {[]any{&rawText}, `["foo"]`, true},
{&[]interface{}{&rawText}, `["foo"]`, true}, {&[]any{&rawText}, `["foo"]`, true},
{struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458 {struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, // Issue6458
{&struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true}, {&struct{ M RawMessage }{rawText}, `{"M":"foo"}`, true},
{struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true}, {struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true},
{&struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true}, {&struct{ M *RawMessage }{&rawText}, `{"M":"foo"}`, true},
{map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 {map[string]any{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458
{&map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 {&map[string]any{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458
{map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, {map[string]any{"M": &rawText}, `{"M":"foo"}`, true},
{&map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, {&map[string]any{"M": &rawText}, `{"M":"foo"}`, true},
{T1{rawText}, `{"M":"foo"}`, true}, // Issue6458 {T1{rawText}, `{"M":"foo"}`, true}, // Issue6458
{T2{&rawText}, `{"M":"foo"}`, true}, {T2{&rawText}, `{"M":"foo"}`, true},
{&T1{rawText}, `{"M":"foo"}`, true}, {&T1{rawText}, `{"M":"foo"}`, true},

View File

@ -200,7 +200,7 @@ func ExampleRawMessage_unmarshal() {
} }
for _, c := range colors { for _, c := range colors {
var dst interface{} var dst any
switch c.Space { switch c.Space {
case "RGB": case "RGB":
dst = new(RGB) dst = new(RGB)

View File

@ -232,7 +232,7 @@ func initBig() {
jsonBig = b jsonBig = b
} }
func genValue(n int) interface{} { func genValue(n int) any {
if n > 1 { if n > 1 {
switch rand.Intn(2) { switch rand.Intn(2) {
case 0: case 0:
@ -265,7 +265,7 @@ func genString(stddev float64) string {
return string(c) return string(c)
} }
func genArray(n int) []interface{} { func genArray(n int) []any {
f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2))) f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2)))
if f > n { if f > n {
f = n f = n
@ -273,14 +273,14 @@ func genArray(n int) []interface{} {
if f < 1 { if f < 1 {
f = 1 f = 1
} }
x := make([]interface{}, f) x := make([]any, f)
for i := range x { for i := range x {
x[i] = genValue(((i+1)*n)/f - (i*n)/f) x[i] = genValue(((i+1)*n)/f - (i*n)/f)
} }
return x return x
} }
func genMap(n int) map[string]interface{} { func genMap(n int) map[string]any {
f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2))) f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2)))
if f > n { if f > n {
f = n f = n
@ -288,7 +288,7 @@ func genMap(n int) map[string]interface{} {
if n > 0 && f == 0 { if n > 0 && f == 0 {
f = 1 f = 1
} }
x := make(map[string]interface{}) x := make(map[string]any)
for i := 0; i < f; i++ { for i := 0; i < f; i++ {
x[genString(10)] = genValue(((i+1)*n)/f - (i*n)/f) x[genString(10)] = genValue(((i+1)*n)/f - (i*n)/f)
} }

View File

@ -53,7 +53,7 @@ func isValidNumber(n string) bool {
return true return true
} }
func assertErrorPresence(t *testing.T, expected error, actual error, prefixes ...interface{}) { func assertErrorPresence(t *testing.T, expected error, actual error, prefixes ...any) {
if expected != nil && actual == nil { if expected != nil && actual == nil {
errorWithPrefixes(t, prefixes, "expected error, but did not get an error") errorWithPrefixes(t, prefixes, "expected error, but did not get an error")
} else if expected == nil && actual != nil { } else if expected == nil && actual != nil {
@ -61,7 +61,7 @@ func assertErrorPresence(t *testing.T, expected error, actual error, prefixes ..
} }
} }
func errorWithPrefixes(t *testing.T, prefixes []interface{}, format string, elements ...interface{}) { func errorWithPrefixes(t *testing.T, prefixes []any, format string, elements ...any) {
fullFormat := format fullFormat := format
allElements := append(prefixes, elements...) allElements := append(prefixes, elements...)

View File

@ -73,7 +73,7 @@ type unicodeTag struct {
} }
var structTagObjectKeyTests = []struct { var structTagObjectKeyTests = []struct {
raw interface{} raw any
value string value string
key string key string
}{ }{
@ -101,12 +101,12 @@ func TestStructTagObjectKey(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("Marshal(%#q) failed: %v", tt.raw, err) t.Fatalf("Marshal(%#q) failed: %v", tt.raw, err)
} }
var f interface{} var f any
err = Unmarshal(b, &f) err = Unmarshal(b, &f)
if err != nil { if err != nil {
t.Fatalf("Unmarshal(%#q) failed: %v", b, err) t.Fatalf("Unmarshal(%#q) failed: %v", b, err)
} }
for i, v := range f.(map[string]interface{}) { for i, v := range f.(map[string]any) {
switch i { switch i {
case tt.key: case tt.key:
if s, ok := v.(string); !ok || s != tt.value { if s, ok := v.(string); !ok || s != tt.value {

View File

@ -122,7 +122,7 @@ const (
// Append acts like Marshal but appends the json representation to b instead of // Append acts like Marshal but appends the json representation to b instead of
// always reallocating a new slice. // always reallocating a new slice.
func Append(b []byte, x interface{}, flags AppendFlags, clrs internal.Colors, indenter *Indenter) ([]byte, error) { func Append(b []byte, x any, flags AppendFlags, clrs internal.Colors, indenter *Indenter) ([]byte, error) {
if x == nil { if x == nil {
// Special case for nil values because it makes the rest of the code // Special case for nil values because it makes the rest of the code
// simpler to assume that it won't be seeing nil pointers. // simpler to assume that it won't be seeing nil pointers.
@ -160,7 +160,7 @@ func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
} }
// Marshal is documented at https://golang.org/pkg/encoding/json/#Marshal // Marshal is documented at https://golang.org/pkg/encoding/json/#Marshal
func Marshal(x interface{}) ([]byte, error) { func Marshal(x any) ([]byte, error) {
var err error var err error
var buf = encoderBufferPool.Get().(*encoderBuffer) var buf = encoderBufferPool.Get().(*encoderBuffer)
@ -175,7 +175,7 @@ func Marshal(x interface{}) ([]byte, error) {
} }
// MarshalIndent is documented at https://golang.org/pkg/encoding/json/#MarshalIndent // MarshalIndent is documented at https://golang.org/pkg/encoding/json/#MarshalIndent
func MarshalIndent(x interface{}, prefix, indent string) ([]byte, error) { func MarshalIndent(x any, prefix, indent string) ([]byte, error) {
b, err := Marshal(x) b, err := Marshal(x)
if err == nil { if err == nil {
@ -190,7 +190,7 @@ func MarshalIndent(x interface{}, prefix, indent string) ([]byte, error) {
} }
// Unmarshal is documented at https://golang.org/pkg/encoding/json/#Unmarshal // Unmarshal is documented at https://golang.org/pkg/encoding/json/#Unmarshal
func Unmarshal(b []byte, x interface{}) error { func Unmarshal(b []byte, x any) error {
r, err := Parse(b, x, 0) r, err := Parse(b, x, 0)
if len(r) != 0 { if len(r) != 0 {
if _, ok := err.(*SyntaxError); !ok { if _, ok := err.(*SyntaxError); !ok {
@ -205,7 +205,7 @@ func Unmarshal(b []byte, x interface{}) error {
// Parse behaves like Unmarshal but the caller can pass a set of flags to // Parse behaves like Unmarshal but the caller can pass a set of flags to
// configure the parsing behavior. // configure the parsing behavior.
func Parse(b []byte, x interface{}, flags ParseFlags) ([]byte, error) { func Parse(b []byte, x any, flags ParseFlags) ([]byte, error) {
t := reflect.TypeOf(x) t := reflect.TypeOf(x)
p := (*iface)(unsafe.Pointer(&x)).ptr p := (*iface)(unsafe.Pointer(&x)).ptr
@ -258,7 +258,7 @@ func (dec *Decoder) Buffered() io.Reader {
} }
// Decode is documented at https://golang.org/pkg/encoding/json/#Decoder.Decode // Decode is documented at https://golang.org/pkg/encoding/json/#Decoder.Decode
func (dec *Decoder) Decode(v interface{}) error { func (dec *Decoder) Decode(v any) error {
raw, err := dec.readValue() raw, err := dec.readValue()
if err != nil { if err != nil {
return err return err
@ -391,7 +391,7 @@ func (enc *Encoder) SetColors(c internal.Colors) {
} }
// Encode is documented at https://golang.org/pkg/encoding/json/#Encoder.Encode // Encode is documented at https://golang.org/pkg/encoding/json/#Encoder.Encode
func (enc *Encoder) Encode(v interface{}) error { func (enc *Encoder) Encode(v any) error {
if enc.err != nil { if enc.err != nil {
return enc.err return enc.err
} }
@ -454,7 +454,7 @@ func (enc *Encoder) SetTrustRawMessage(on bool) {
} }
var encoderBufferPool = sync.Pool{ var encoderBufferPool = sync.Pool{
New: func() interface{} { return &encoderBuffer{data: make([]byte, 0, 4096)} }, New: func() any { return &encoderBuffer{data: make([]byte, 0, 4096)} },
} }
type encoderBuffer struct{ data []byte } type encoderBuffer struct{ data []byte }

View File

@ -33,8 +33,8 @@ type testSyntaxError struct {
func (e *testSyntaxError) Error() string { return e.msg } func (e *testSyntaxError) Error() string { return e.msg }
var ( var (
marshal func([]byte, interface{}) ([]byte, error) marshal func([]byte, any) ([]byte, error)
unmarshal func([]byte, interface{}) error unmarshal func([]byte, any) error
escapeHTML bool escapeHTML bool
) )
@ -50,7 +50,7 @@ func TestMain(m *testing.M) {
enc := json.NewEncoder(buf) enc := json.NewEncoder(buf)
enc.SetEscapeHTML(escapeHTML) enc.SetEscapeHTML(escapeHTML)
marshal = func(b []byte, v interface{}) ([]byte, error) { marshal = func(b []byte, v any) ([]byte, error) {
buf.data = b buf.data = b
err := enc.Encode(v) err := enc.Encode(v)
return buf.data, err return buf.data, err
@ -64,11 +64,11 @@ func TestMain(m *testing.M) {
flags |= EscapeHTML flags |= EscapeHTML
} }
marshal = func(b []byte, v interface{}) ([]byte, error) { marshal = func(b []byte, v any) ([]byte, error) {
return Append(b, v, flags, internal.Colors{}, nil) return Append(b, v, flags, internal.Colors{}, nil)
} }
unmarshal = func(b []byte, v interface{}) error { unmarshal = func(b []byte, v any) error {
_, err := Parse(b, v, ZeroCopy) _, err := Parse(b, v, ZeroCopy)
return err return err
} }
@ -88,7 +88,7 @@ type tree struct {
Right *tree Right *tree
} }
var testValues = [...]interface{}{ var testValues = [...]any{
// constants // constants
nil, nil,
false, false,
@ -181,7 +181,7 @@ var testValues = [...]interface{}{
makeSlice(250), makeSlice(250),
makeSlice(1020), makeSlice(1020),
[]string{"A", "B", "C"}, []string{"A", "B", "C"},
[]interface{}{nil, true, false, 0.5, "Hello World!"}, []any{nil, true, false, 0.5, "Hello World!"},
// map // map
makeMapStringBool(0), makeMapStringBool(0),
@ -213,7 +213,7 @@ var testValues = [...]interface{}{
S string S string
}{42, time.Date(2016, 12, 20, 0, 20, 1, 0, time.UTC), "Hello World!"}, }{42, time.Date(2016, 12, 20, 0, 20, 1, 0, time.UTC), "Hello World!"},
// These types are interesting because they fit in a pointer so the compiler // These types are interesting because they fit in a pointer so the compiler
// puts their value directly into the pointer field of the interface{} that // puts their value directly into the pointer field of the any that
// is passed to Marshal. // is passed to Marshal.
struct{ X *int }{}, struct{ X *int }{},
struct{ X *int }{new(int)}, struct{ X *int }{new(int)},
@ -226,9 +226,9 @@ var testValues = [...]interface{}{
A string `json:"name"` A string `json:"name"`
B string `json:"-"` B string `json:"-"`
C string `json:",omitempty"` C string `json:",omitempty"`
D map[string]interface{} `json:",string"` D map[string]any `json:",string"`
e string e string
}{A: "Luke", D: map[string]interface{}{"answer": float64(42)}}, }{A: "Luke", D: map[string]any{"answer": float64(42)}},
struct{ point }{point{1, 2}}, struct{ point }{point{1, 2}},
tree{ tree{
Value: "T", Value: "T",
@ -258,7 +258,7 @@ var testValues = [...]interface{}{
loadTestdata(filepath.Join(runtime.GOROOT(), "src/encoding/json/testdata/code.json.gz")), loadTestdata(filepath.Join(runtime.GOROOT(), "src/encoding/json/testdata/code.json.gz")),
} }
var durationTestValues = []interface{}{ var durationTestValues = []any{
// duration // duration
time.Nanosecond, time.Nanosecond,
time.Microsecond, time.Microsecond,
@ -287,15 +287,15 @@ func makeMapStringBool(n int) map[string]bool {
return m return m
} }
func makeMapStringInterface(n int) map[string]interface{} { func makeMapStringInterface(n int) map[string]any {
m := make(map[string]interface{}, n) m := make(map[string]any, n)
for i := 0; i != n; i++ { for i := 0; i != n; i++ {
m[strconv.Itoa(i)] = nil m[strconv.Itoa(i)] = nil
} }
return m return m
} }
func testName(v interface{}) string { func testName(v any) string {
return fmt.Sprintf("%T", v) return fmt.Sprintf("%T", v)
} }
@ -314,7 +314,7 @@ type codeNode2 struct {
MeanT int64 `json:"mean_t"` MeanT int64 `json:"mean_t"`
} }
func loadTestdata(path string) interface{} { func loadTestdata(path string) any {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
return err.Error() return err.Error()
@ -465,7 +465,7 @@ func TestCodecDuration(t *testing.T) {
} }
} }
func newValue(model interface{}) reflect.Value { func newValue(model any) reflect.Value {
if model == nil { if model == nil {
return reflect.New(reflect.TypeOf(&model).Elem()) return reflect.New(reflect.TypeOf(&model).Elem())
} }
@ -790,7 +790,7 @@ func TestDontMatchCaseIncensitiveStructFields(t *testing.T) {
func TestMarshalFuzzBugs(t *testing.T) { func TestMarshalFuzzBugs(t *testing.T) {
tests := []struct { tests := []struct {
value interface{} value any
output string output string
}{ }{
{ // html sequences are escaped even in RawMessage { // html sequences are escaped even in RawMessage
@ -826,27 +826,27 @@ func TestMarshalFuzzBugs(t *testing.T) {
func TestUnmarshalFuzzBugs(t *testing.T) { func TestUnmarshalFuzzBugs(t *testing.T) {
tests := []struct { tests := []struct {
input string input string
value interface{} value any
}{ }{
{ // non-UTF8 sequences must be converted to the utf8.RuneError character. { // non-UTF8 sequences must be converted to the utf8.RuneError character.
input: "[\"00000\xef\"]", input: "[\"00000\xef\"]",
value: []interface{}{"00000<30>"}, value: []any{"00000<30>"},
}, },
{ // UTF16 surrogate followed by null character { // UTF16 surrogate followed by null character
input: "[\"\\ud800\\u0000\"]", input: "[\"\\ud800\\u0000\"]",
value: []interface{}{"<22>\x00"}, value: []any{"<22>\x00"},
}, },
{ // UTF16 surrogate followed by ascii character { // UTF16 surrogate followed by ascii character
input: "[\"\\uDF00\\u000e\"]", input: "[\"\\uDF00\\u000e\"]",
value: []interface{}{"<22>\x0e"}, value: []any{"<22>\x0e"},
}, },
{ // UTF16 surrogate followed by unicode character { // UTF16 surrogate followed by unicode character
input: "[[\"\\uDF00\\u0800\"]]", input: "[[\"\\uDF00\\u0800\"]]",
value: []interface{}{[]interface{}{"<22>ࠀ"}}, value: []any{[]any{"<22>ࠀ"}},
}, },
{ // invalid UTF16 surrogate sequenced followed by a valid UTF16 surrogate sequence { // invalid UTF16 surrogate sequenced followed by a valid UTF16 surrogate sequence
input: "[\"\\udf00\\udb00\\udf00\"]", input: "[\"\\udf00\\udb00\\udf00\"]",
value: []interface{}{"<22>\U000d0300"}, value: []any{"<22>\U000d0300"},
}, },
{ // decode single-element slice into []byte field { // decode single-element slice into []byte field
input: "{\"f\":[0],\"0\":[0]}", input: "{\"f\":[0],\"0\":[0]}",
@ -893,7 +893,7 @@ func TestUnmarshalFuzzBugs(t *testing.T) {
}, },
{ // random ASCII character { // random ASCII character
input: "}", input: "}",
value: []interface{}{}, value: []any{},
}, },
{ // random byte after valid JSON, decoded to a nil type { // random byte after valid JSON, decoded to a nil type
input: "0\x93", input: "0\x93",
@ -904,23 +904,23 @@ func TestUnmarshalFuzzBugs(t *testing.T) {
}, },
{ // random byte after valid JSON, decoded to a slice type { // random byte after valid JSON, decoded to a slice type
input: "0\x93", input: "0\x93",
value: []interface{}{}, value: []any{},
}, },
{ // decode integer into slice { // decode integer into slice
input: "0", input: "0",
value: []interface{}{}, value: []any{},
}, },
{ // decode integer with trailing space into slice { // decode integer with trailing space into slice
input: "0\t", input: "0\t",
value: []interface{}{}, value: []any{},
}, },
{ // decode integer with leading random bytes into slice { // decode integer with leading random bytes into slice
input: "\b0", input: "\b0",
value: []interface{}{}, value: []any{},
}, },
{ // decode string into slice followed by number { // decode string into slice followed by number
input: "\"\"0", input: "\"\"0",
value: []interface{}{}, value: []any{},
}, },
{ // decode what looks like an object followed by a number into a string { // decode what looks like an object followed by a number into a string
input: "{0", input: "{0",
@ -943,15 +943,15 @@ func TestUnmarshalFuzzBugs(t *testing.T) {
}, },
{ // decode what looks like an array followed by a number into a slice { // decode what looks like an array followed by a number into a slice
input: "[9E600", input: "[9E600",
value: []interface{}{}, value: []any{},
}, },
{ // decode a number which is too large to fit in a float64 { // decode a number which is too large to fit in a float64
input: "[1e900]", input: "[1e900]",
value: []interface{}{}, value: []any{},
}, },
{ // many nested arrays openings { // many nested arrays openings
input: "[[[[[[", input: "[[[[[[",
value: []interface{}{}, value: []any{},
}, },
{ // decode a map with value type mismatch and missing closing character { // decode a map with value type mismatch and missing closing character
input: "{\"\":0", input: "{\"\":0",
@ -985,7 +985,7 @@ func TestUnmarshalFuzzBugs(t *testing.T) {
}, },
{ // decode object with null key into map { // decode object with null key into map
input: "{null:0}", input: "{null:0}",
value: map[string]interface{}{}, value: map[string]any{},
}, },
{ // decode unquoted integer into struct field with string tag { // decode unquoted integer into struct field with string tag
input: "{\"S\":0}", input: "{\"S\":0}",
@ -1154,8 +1154,8 @@ func TestUnmarshalFuzzBugs(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
var ptr1 interface{} var ptr1 any
var ptr2 interface{} var ptr2 any
if test.value != nil { if test.value != nil {
ptr1 = reflect.New(reflect.TypeOf(test.value)).Interface() ptr1 = reflect.New(reflect.TypeOf(test.value)).Interface()
@ -1279,7 +1279,7 @@ func TestGithubIssue13(t *testing.T) {
func TestGithubIssue15(t *testing.T) { func TestGithubIssue15(t *testing.T) {
// https://github.com/segmentio/encoding/issues/15 // https://github.com/segmentio/encoding/issues/15
tests := []struct { tests := []struct {
m interface{} m any
s string s string
}{ }{
{ {
@ -1346,7 +1346,7 @@ type structD struct{ M encoding.TextMarshaler }
func TestGithubIssue16(t *testing.T) { func TestGithubIssue16(t *testing.T) {
// https://github.com/segmentio/encoding/issues/16 // https://github.com/segmentio/encoding/issues/16
tests := []struct { tests := []struct {
value interface{} value any
output string output string
}{ }{
{value: sliceA(nil), output: `"A"`}, {value: sliceA(nil), output: `"A"`},
@ -1515,7 +1515,7 @@ func TestGithubIssue23(t *testing.T) {
} }
func TestGithubIssue26(t *testing.T) { func TestGithubIssue26(t *testing.T) {
type interfaceType interface{} type interfaceType any
var value interfaceType var value interfaceType
var data = []byte(`{}`) var data = []byte(`{}`)

View File

@ -53,7 +53,7 @@ type stdWriter struct {
recsWritten bool recsWritten bool
tpl *stdTemplate tpl *stdTemplate
encodeFns []func(b []byte, v interface{}) ([]byte, error) encodeFns []func(b []byte, v any) ([]byte, error)
} }
// Open implements output.RecordWriter. // Open implements output.RecordWriter.
@ -295,7 +295,7 @@ type lineRecordWriter struct {
tpl [][]byte tpl [][]byte
// encodeFns holds an encoder func for each element of the record. // encodeFns holds an encoder func for each element of the record.
encodeFns []func(b []byte, v interface{}) ([]byte, error) encodeFns []func(b []byte, v any) ([]byte, error)
} }
// Open implements output.RecordWriter. // Open implements output.RecordWriter.

View File

@ -25,7 +25,7 @@ func NewMetadataWriter(out io.Writer, fm *output.Formatting) output.MetadataWrit
return &mdWriter{out: out, fm: fm} return &mdWriter{out: out, fm: fm}
} }
func (w *mdWriter) write(v interface{}) error { func (w *mdWriter) write(v any) error {
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
enc := jcolorenc.NewEncoder(buf) enc := jcolorenc.NewEncoder(buf)

View File

@ -138,12 +138,12 @@ func (t *Table) getCellTrans(row int, col int) textTransFunc {
cellTrans := t.cellTrans[key] cellTrans := t.cellTrans[key]
if cellTrans == nil { if cellTrans == nil {
cellTrans = func(val ...interface{}) string { cellTrans = func(val ...any) string {
return fmt.Sprint(val...) return fmt.Sprint(val...)
} }
} }
return func(val ...interface{}) string { return func(val ...any) string {
return cellTrans(colTrans(val...)) return cellTrans(colTrans(val...))
} }
} }
@ -155,7 +155,7 @@ func (t *Table) getColTrans(col int) textTransFunc {
return trans return trans
} }
return func(val ...interface{}) string { return func(val ...any) string {
return fmt.Sprint(val...) return fmt.Sprint(val...)
} }
} }
@ -571,4 +571,4 @@ func (t *Table) parseDimension(str string, colKey, rowKey int) []string {
// textTransFunc is a function that can transform text, typically // textTransFunc is a function that can transform text, typically
// to add color. // to add color.
type textTransFunc func(a ...interface{}) string type textTransFunc func(a ...any) string

View File

@ -35,7 +35,7 @@ type table struct {
tblImpl *internal.Table tblImpl *internal.Table
} }
func (t *table) renderResultCell(knd kind.Kind, val interface{}) string { func (t *table) renderResultCell(knd kind.Kind, val any) string {
switch val := val.(type) { switch val := val.(type) {
case string: case string:
return val return val

View File

@ -42,7 +42,7 @@ type recordWriter struct {
tplFieldStart []string tplFieldStart []string
tplFieldEnd []string tplFieldEnd []string
fieldPrintFns []func(w io.Writer, a ...interface{}) fieldPrintFns []func(w io.Writer, a ...any)
} }
const ( const (
@ -66,7 +66,7 @@ func (w *recordWriter) Open(recMeta sqlz.RecordMeta) error {
newline = "\n" newline = "\n"
} }
w.fieldPrintFns = make([]func(w io.Writer, a ...interface{}), len(recMeta)) w.fieldPrintFns = make([]func(w io.Writer, a ...any), len(recMeta))
w.tplFieldStart = make([]string, len(recMeta)) w.tplFieldStart = make([]string, len(recMeta))
w.tplFieldEnd = make([]string, len(recMeta)) w.tplFieldEnd = make([]string, len(recMeta))
@ -107,7 +107,7 @@ func (w *recordWriter) Open(recMeta sqlz.RecordMeta) error {
// monoPrint delegates to fmt.Fprint, for // monoPrint delegates to fmt.Fprint, for
// monochrome (non-color) printing. // monochrome (non-color) printing.
func monoPrint(w io.Writer, a ...interface{}) { func monoPrint(w io.Writer, a ...any) {
_, _ = fmt.Fprint(w, a...) _, _ = fmt.Fprint(w, a...)
} }

View File

@ -155,10 +155,10 @@ func execInsert(ctx context.Context, recw libsq.RecordWriter, recMeta sqlz.Recor
} }
} }
// mungeCSV2InsertRecord returns a new []interface{} containing // mungeCSV2InsertRecord returns a new []any containing
// the values of the csvRec []string. // the values of the csvRec []string.
func mungeCSV2InsertRecord(csvRec []string) []interface{} { func mungeCSV2InsertRecord(csvRec []string) []any {
a := make([]interface{}, len(csvRec)) a := make([]any, len(csvRec))
for i := range csvRec { for i := range csvRec {
a[i] = csvRec[i] a[i] = csvRec[i]
} }

View File

@ -79,7 +79,7 @@ const (
// of fieldName:fieldValue. For a nested JSON object, the value set // of fieldName:fieldValue. For a nested JSON object, the value set
// may refer to several entities, and thus may decompose into // may refer to several entities, and thus may decompose into
// insertions to several tables. // insertions to several tables.
type objectValueSet map[*entity]map[string]interface{} type objectValueSet map[*entity]map[string]any
// processor process JSON objects. // processor process JSON objects.
type processor struct { type processor struct {
@ -200,7 +200,7 @@ func (p *processor) buildSchemaFlat() (*importSchema, error) {
// processObject processes the parsed JSON object m. If the structure // processObject processes the parsed JSON object m. If the structure
// of the importSchema changes due to this object, dirtySchema returns true. // of the importSchema changes due to this object, dirtySchema returns true.
func (p *processor) processObject(m map[string]interface{}, chunk []byte) (dirtySchema bool, err error) { func (p *processor) processObject(m map[string]any, chunk []byte) (dirtySchema bool, err error) {
p.curObjVals = objectValueSet{} p.curObjVals = objectValueSet{}
err = p.doAddObject(p.root, m) err = p.doAddObject(p.root, m)
dirtySchema = len(p.schemaDirtyEntities) > 0 dirtySchema = len(p.schemaDirtyEntities) > 0
@ -233,10 +233,10 @@ func (p *processor) updateColNames(chunk []byte) error {
return nil return nil
} }
func (p *processor) doAddObject(ent *entity, m map[string]interface{}) error { func (p *processor) doAddObject(ent *entity, m map[string]any) error {
for fieldName, val := range m { for fieldName, val := range m {
switch val := val.(type) { switch val := val.(type) {
case map[string]interface{}: case map[string]any:
// time to recurse // time to recurse
child := ent.getChild(fieldName) child := ent.getChild(fieldName)
if child == nil { if child == nil {
@ -268,7 +268,7 @@ func (p *processor) doAddObject(ent *entity, m map[string]interface{}) error {
return err return err
} }
case []interface{}: case []any:
if !stringz.InSlice(ent.fieldNames, fieldName) { if !stringz.InSlice(ent.fieldNames, fieldName) {
ent.fieldNames = append(ent.fieldNames, fieldName) ent.fieldNames = append(ent.fieldNames, fieldName)
} }
@ -289,7 +289,7 @@ func (p *processor) doAddObject(ent *entity, m map[string]interface{}) error {
var entVals = p.curObjVals[ent] var entVals = p.curObjVals[ent]
if entVals == nil { if entVals == nil {
entVals = map[string]interface{}{} entVals = map[string]any{}
p.curObjVals[ent] = entVals p.curObjVals[ent] = entVals
} }
@ -318,7 +318,7 @@ func (p *processor) buildInsertionsFlat(schema *importSchema) ([]*insertion, err
// Each of unwrittenObjVals is effectively an INSERT row // Each of unwrittenObjVals is effectively an INSERT row
for _, objValSet := range p.unwrittenObjVals { for _, objValSet := range p.unwrittenObjVals {
var colNames []string var colNames []string
colVals := map[string]interface{}{} colVals := map[string]any{}
for ent, fieldVals := range objValSet { for ent, fieldVals := range objValSet {
// For each entity, we get its values and add them to colVals. // For each entity, we get its values and add them to colVals.
@ -333,7 +333,7 @@ func (p *processor) buildInsertionsFlat(schema *importSchema) ([]*insertion, err
} }
sort.Strings(colNames) sort.Strings(colNames)
vals := make([]interface{}, len(colNames)) vals := make([]any, len(colNames))
for i, colName := range colNames { for i, colName := range colNames {
vals[i] = colVals[colName] vals[i] = colVals[colName]
} }
@ -627,10 +627,10 @@ type insertion struct {
tbl string tbl string
cols []string cols []string
vals []interface{} vals []any
} }
func newInsertion(tbl string, cols []string, vals []interface{}) *insertion { func newInsertion(tbl string, cols []string, vals []any) *insertion {
return &insertion{ return &insertion{
stmtKey: buildInsertStmtKey(tbl, cols), stmtKey: buildInsertStmtKey(tbl, cols),
tbl: tbl, tbl: tbl,

View File

@ -54,7 +54,7 @@ func DetectJSON(ctx context.Context, log lg.Log, openFn source.FileOpenFunc) (de
defer log.WarnIfCloseError(r2) defer log.WarnIfCloseError(r2)
dec = stdj.NewDecoder(io.TeeReader(r2, buf)) dec = stdj.NewDecoder(io.TeeReader(r2, buf))
var m map[string]interface{} var m map[string]any
err = dec.Decode(&m) err = dec.Decode(&m)
if err != nil { if err != nil {
return source.TypeNone, 0, nil return source.TypeNone, 0, nil
@ -97,7 +97,7 @@ func DetectJSON(ctx context.Context, log lg.Log, openFn source.FileOpenFunc) (de
sc := newObjectInArrayScanner(r2) sc := newObjectInArrayScanner(r2)
var validObjCount int var validObjCount int
var obj map[string]interface{} var obj map[string]any
for { for {
select { select {
@ -148,7 +148,7 @@ func importJSON(ctx context.Context, log lg.Log, job importJob) error {
scan := newObjectInArrayScanner(r) scan := newObjectInArrayScanner(r)
var ( var (
obj map[string]interface{} obj map[string]any
chunk []byte chunk []byte
schemaModified bool schemaModified bool
curSchema *importSchema curSchema *importSchema
@ -296,7 +296,7 @@ func newObjectInArrayScanner(r io.Reader) *objectsInArrayScanner {
// next scans the next object from the reader. The returned chunk holds // next scans the next object from the reader. The returned chunk holds
// the raw JSON that the obj was decoded from. When no more objects, // the raw JSON that the obj was decoded from. When no more objects,
// obj and chunk are nil. // obj and chunk are nil.
func (s *objectsInArrayScanner) next() (obj map[string]interface{}, chunk []byte, err error) { func (s *objectsInArrayScanner) next() (obj map[string]any, chunk []byte, err error) {
var tok stdj.Token var tok stdj.Token
if s.bufOffset == 0 { if s.bufOffset == 0 {

View File

@ -55,18 +55,18 @@ func DetectJSONA(ctx context.Context, log lg.Log, openFn source.FileOpenFunc) (d
return source.TypeNone, 0, nil return source.TypeNone, 0, nil
} }
// If the line is JSONA, it should marshall into []interface{} // If the line is JSONA, it should marshall into []any
var fields []interface{} var fields []any
err = stdj.Unmarshal(line, &fields) err = stdj.Unmarshal(line, &fields)
if err != nil { if err != nil {
return source.TypeNone, 0, nil return source.TypeNone, 0, nil
} }
// JSONA must consist only of values, not objects. Any object // JSONA must consist only of values, not objects. Any object
// would get marshalled into a map[string]interface{}, so // would get marshalled into a map[string]any, so
// we check for that. // we check for that.
for _, field := range fields { for _, field := range fields {
if _, ok := field.(map[string]interface{}); ok { if _, ok := field.(map[string]any); ok {
return source.TypeNone, 0, nil return source.TypeNone, 0, nil
} }
} }
@ -180,8 +180,8 @@ func startInsertJSONA(ctx context.Context, recordCh chan<- sqlz.Record, errCh <-
return errz.New("malformed JSONA input") return errz.New("malformed JSONA input")
} }
// If the line is JSONA, it should marshal into []interface{} // If the line is JSONA, it should marshal into []any
var rec []interface{} var rec []any
err = stdj.Unmarshal(line, &rec) err = stdj.Unmarshal(line, &rec)
if err != nil { if err != nil {
return errz.Err(err) return errz.Err(err)
@ -259,8 +259,8 @@ func detectColKindsJSONA(ctx context.Context, r io.Reader) ([]kind.Kind, []kind.
return nil, nil, errz.New("line does not begin with left bracket '['") return nil, nil, errz.New("line does not begin with left bracket '['")
} }
// If the line is JSONA, it should marshall into []interface{} // If the line is JSONA, it should marshall into []any
var vals []interface{} var vals []any
err = stdj.Unmarshal(line, &vals) err = stdj.Unmarshal(line, &vals)
if err != nil { if err != nil {
return nil, nil, errz.Err(err) return nil, nil, errz.Err(err)
@ -316,7 +316,7 @@ func detectColKindsJSONA(ctx context.Context, r io.Reader) ([]kind.Kind, []kind.
// (especially important for id columns). // (especially important for id columns).
// So, if the float64 has zero after the decimal point '.' (that // So, if the float64 has zero after the decimal point '.' (that
// is to say, it's a round float like 1.0), we return the int64 value. // is to say, it's a round float like 1.0), we return the int64 value.
func maybeFloatToInt(val interface{}) interface{} { func maybeFloatToInt(val any) any {
if f64, ok := val.(float64); ok { if f64, ok := val.(float64); ok {
floor := math.Floor(f64) floor := math.Floor(f64)
if f64-floor == 0 { if f64-floor == 0 {

View File

@ -50,8 +50,8 @@ func DetectJSONL(ctx context.Context, log lg.Log, openFn source.FileOpenFunc) (d
return source.TypeNone, 0, nil return source.TypeNone, 0, nil
} }
// If the line is JSONL, it should marshall into map[string]interface{} // If the line is JSONL, it should marshall into map[string]any
var vals map[string]interface{} var vals map[string]any
err = stdj.Unmarshal(line, &vals) err = stdj.Unmarshal(line, &vals)
if err != nil { if err != nil {
return source.TypeNone, 0, nil return source.TypeNone, 0, nil
@ -147,7 +147,7 @@ func importJSONL(ctx context.Context, log lg.Log, job importJob) error {
} }
} }
var m map[string]interface{} var m map[string]any
dec := stdj.NewDecoder(bytes.NewReader(line)) dec := stdj.NewDecoder(bytes.NewReader(line))
err = dec.Decode(&m) err = dec.Decode(&m)

View File

@ -121,18 +121,18 @@ func TestImportJSON_Flat(t *testing.T) {
func TestScanObjectsInArray(t *testing.T) { func TestScanObjectsInArray(t *testing.T) {
var ( var (
m1 = []map[string]interface{}{{"a": float64(1)}} m1 = []map[string]any{{"a": float64(1)}}
m2 = []map[string]interface{}{{"a": float64(1)}, {"a": float64(2)}} m2 = []map[string]any{{"a": float64(1)}, {"a": float64(2)}}
m3 = []map[string]interface{}{{"a": float64(1)}, {"a": float64(2)}, {"a": float64(3)}} m3 = []map[string]any{{"a": float64(1)}, {"a": float64(2)}, {"a": float64(3)}}
m4 = []map[string]interface{}{ m4 = []map[string]any{
{"a": float64(1), "b": []interface{}{float64(1), float64(2), float64(3)}, "c": map[string]interface{}{"c1": float64(1)}, "d": "d1"}, {"a": float64(1), "b": []any{float64(1), float64(2), float64(3)}, "c": map[string]any{"c1": float64(1)}, "d": "d1"},
{"a": float64(2), "b": []interface{}{float64(21), float64(22), float64(23)}, "c": map[string]interface{}{"c1": float64(2)}, "d": "d2"}, {"a": float64(2), "b": []any{float64(21), float64(22), float64(23)}, "c": map[string]any{"c1": float64(2)}, "d": "d2"},
} }
) )
testCases := []struct { testCases := []struct {
in string in string
wantObjs []map[string]interface{} wantObjs []map[string]any
wantChunks []string wantChunks []string
wantErr bool wantErr bool
}{ }{

View File

@ -66,11 +66,11 @@ func TestDetectColKindsJSONA(t *testing.T) {
// ScanObjectsInArray is a convenience function // ScanObjectsInArray is a convenience function
// for objectsInArrayScanner. // for objectsInArrayScanner.
func ScanObjectsInArray(r io.Reader) (objs []map[string]interface{}, chunks [][]byte, err error) { func ScanObjectsInArray(r io.Reader) (objs []map[string]any, chunks [][]byte, err error) {
sc := newObjectInArrayScanner(r) sc := newObjectInArrayScanner(r)
for { for {
var obj map[string]interface{} var obj map[string]any
var chunk []byte var chunk []byte
obj, chunk, err = sc.next() obj, chunk, err = sc.next()

View File

@ -29,7 +29,7 @@ const typeTestTableDDLPath = "testdata/type_test.ddl"
// - Row 1 contains non-zero values. // - Row 1 contains non-zero values.
// - Row 2 contains non-zero values and nil values for cols that permit // - Row 2 contains non-zero values and nil values for cols that permit
// nil values (those cols ending with _n such as col_text_n). // nil values (those cols ending with _n such as col_text_n).
var typeTestVals = [][]interface{}{ var typeTestVals = [][]any{
{ {
1, // col_id 1, // col_id
fixt.IntZ, // col_bigint fixt.IntZ, // col_bigint
@ -376,7 +376,7 @@ func TestDatabaseTypeJSON(t *testing.T) {
)` )`
) )
testVals := [][]interface{}{ testVals := [][]any{
{ {
int64(1), // col_id int64(1), // col_id
fixt.JSON, // col_json fixt.JSON, // col_json

View File

@ -84,7 +84,7 @@ func recordMetaFromColumnTypes(log lg.Log, colTypes []*sql.ColumnType) sqlz.Reco
// In particular mysql.NullTime is unboxed to *time.Time, and TIME fields // In particular mysql.NullTime is unboxed to *time.Time, and TIME fields
// are munged from RawBytes to string. // are munged from RawBytes to string.
func getNewRecordFunc(rowMeta sqlz.RecordMeta) driver.NewRecordFunc { func getNewRecordFunc(rowMeta sqlz.RecordMeta) driver.NewRecordFunc {
return func(row []interface{}) (sqlz.Record, error) { return func(row []any) (sqlz.Record, error) {
rec, skipped := driver.NewRecordFromScanRow(rowMeta, row, nil) rec, skipped := driver.NewRecordFromScanRow(rowMeta, row, nil)
// We iterate over each element of val, checking for certain // We iterate over each element of val, checking for certain
// conditions. A more efficient approach might be to (in // conditions. A more efficient approach might be to (in
@ -507,7 +507,7 @@ var datetimeLayouts = []string{time.RFC3339Nano, time.RFC3339}
// mungeSetDatetimeFromString attempts to parse s into time.Time and // mungeSetDatetimeFromString attempts to parse s into time.Time and
// sets rec[i] to that value. If unable to parse, rec is unchanged, // sets rec[i] to that value. If unable to parse, rec is unchanged,
// and it's up to mysql to deal with the text. // and it's up to mysql to deal with the text.
func mungeSetDatetimeFromString(s string, i int, rec []interface{}) { func mungeSetDatetimeFromString(s string, i int, rec []any) {
var t time.Time var t time.Time
var err error var err error
@ -522,7 +522,7 @@ func mungeSetDatetimeFromString(s string, i int, rec []interface{}) {
// mungeSetZeroValue is invoked when rec[i] is nil, but // mungeSetZeroValue is invoked when rec[i] is nil, but
// destMeta[i] is not nullable. // destMeta[i] is not nullable.
func mungeSetZeroValue(i int, rec []interface{}, destMeta sqlz.RecordMeta) { func mungeSetZeroValue(i int, rec []any, destMeta sqlz.RecordMeta) {
// REVISIT: do we need to do special handling for kind.Datetime // REVISIT: do we need to do special handling for kind.Datetime
// and kind.Time (e.g. "00:00" for time)? // and kind.Time (e.g. "00:00" for time)?
z := reflect.Zero(destMeta[i].ScanType()).Interface() z := reflect.Zero(destMeta[i].ScanType()).Interface()

View File

@ -150,7 +150,7 @@ func (d *driveri) PrepareUpdateStmt(ctx context.Context, db sqlz.DB, destTbl str
} }
func newStmtExecFunc(stmt *sql.Stmt) driver.StmtExecFunc { func newStmtExecFunc(stmt *sql.Stmt) driver.StmtExecFunc {
return func(ctx context.Context, args ...interface{}) (int64, error) { return func(ctx context.Context, args ...any) (int64, error) {
res, err := stmt.ExecContext(ctx, args...) res, err := stmt.ExecContext(ctx, args...)
if err != nil { if err != nil {
return 0, errz.Err(err) return 0, errz.Err(err)

View File

@ -30,7 +30,7 @@ const typeTestTableDDLPath = "testdata/type_test.ddl"
// - Row 1 contains non-zero values. // - Row 1 contains non-zero values.
// - Row 2 contains non-zero values and nil values for cols that permit // - Row 2 contains non-zero values and nil values for cols that permit
// nil values (those cols ending with _n such as col_text_n). // nil values (those cols ending with _n such as col_text_n).
var typeTestVals = [][]interface{}{ var typeTestVals = [][]any{
{ {
1, // col_id 1, // col_id
fixt.IntZ, // col_bigint fixt.IntZ, // col_bigint

View File

@ -100,7 +100,7 @@ func toNullableScanType(log lg.Log, colName, dbTypeName string, knd kind.Kind, p
switch pgScanType { switch pgScanType {
default: default:
// If we don't recognize the scan type (likely it's interface{}), // If we don't recognize the scan type (likely it's any),
// we explicitly switch through the db type names that we know. // we explicitly switch through the db type names that we know.
// At this time, we will use NullString for all unrecognized // At this time, we will use NullString for all unrecognized
// scan types, but nonetheless we switch through the known db type // scan types, but nonetheless we switch through the known db type
@ -515,7 +515,7 @@ func colMetaFromPgColumn(log lg.Log, pgCol *pgColumn) *source.ColMetadata {
// are returned. If tblName is specified, constraints just for that // are returned. If tblName is specified, constraints just for that
// table are returned. // table are returned.
func getPgConstraints(ctx context.Context, log lg.Log, db sqlz.DB, tblName string) ([]*pgConstraint, error) { func getPgConstraints(ctx context.Context, log lg.Log, db sqlz.DB, tblName string) ([]*pgConstraint, error) {
var args []interface{} var args []any
query := `SELECT kcu.table_catalog,kcu.table_schema,kcu.table_name,kcu.column_name, query := `SELECT kcu.table_catalog,kcu.table_schema,kcu.table_name,kcu.column_name,
kcu.ordinal_position,tc.constraint_name,tc.constraint_type, kcu.ordinal_position,tc.constraint_name,tc.constraint_type,
( (

View File

@ -225,7 +225,7 @@ func (d *driveri) PrepareUpdateStmt(ctx context.Context, db sqlz.DB, destTbl str
} }
func newStmtExecFunc(stmt *sql.Stmt) driver.StmtExecFunc { func newStmtExecFunc(stmt *sql.Stmt) driver.StmtExecFunc {
return func(ctx context.Context, args ...interface{}) (int64, error) { return func(ctx context.Context, args ...any) (int64, error) {
res, err := stmt.ExecContext(ctx, args...) res, err := stmt.ExecContext(ctx, args...)
if err != nil { if err != nil {
return 0, errz.Err(err) return 0, errz.Err(err)
@ -414,7 +414,7 @@ func (d *driveri) RecordMeta(colTypes []*sql.ColumnType) (sqlz.RecordMeta, drive
recMeta[i] = sqlz.NewFieldMeta(colTypeData) recMeta[i] = sqlz.NewFieldMeta(colTypeData)
} }
mungeFn := func(vals []interface{}) (sqlz.Record, error) { mungeFn := func(vals []any) (sqlz.Record, error) {
// postgres doesn't need to do any special munging, so we // postgres doesn't need to do any special munging, so we
// just use the default munging. // just use the default munging.
rec, skipped := driver.NewRecordFromScanRow(recMeta, vals, nil) rec, skipped := driver.NewRecordFromScanRow(recMeta, vals, nil)

View File

@ -51,7 +51,7 @@ var typeTestColNames = []string{
// - Row 1 contains non-zero values. // - Row 1 contains non-zero values.
// - Row 2 contains non-zero values and nil values for cols that permit // - Row 2 contains non-zero values and nil values for cols that permit
// nil values (those cols ending with _n such as col_int_n). // nil values (those cols ending with _n such as col_int_n).
var typeTestVals = [][]interface{}{ var typeTestVals = [][]any{
{ {
int64(1), // col_id int64(1), // col_id
fixt.IntZ, // col_int fixt.IntZ, // col_int

View File

@ -214,7 +214,7 @@ func (d *driveri) RecordMeta(colTypes []*sql.ColumnType) (sqlz.RecordMeta, drive
return nil, nil, errz.Err(err) return nil, nil, errz.Err(err)
} }
mungeFn := func(vals []interface{}) (sqlz.Record, error) { mungeFn := func(vals []any) (sqlz.Record, error) {
// sqlite3 doesn't need to do any special munging, so we // sqlite3 doesn't need to do any special munging, so we
// just use the default munging. // just use the default munging.
rec, skipped := driver.NewRecordFromScanRow(recMeta, vals, nil) rec, skipped := driver.NewRecordFromScanRow(recMeta, vals, nil)
@ -325,7 +325,7 @@ func (d *driveri) PrepareUpdateStmt(ctx context.Context, db sqlz.DB, destTbl str
} }
func newStmtExecFunc(stmt *sql.Stmt) driver.StmtExecFunc { func newStmtExecFunc(stmt *sql.Stmt) driver.StmtExecFunc {
return func(ctx context.Context, args ...interface{}) (int64, error) { return func(ctx context.Context, args ...any) (int64, error) {
res, err := stmt.ExecContext(ctx, args...) res, err := stmt.ExecContext(ctx, args...)
if err != nil { if err != nil {
return 0, errz.Err(err) return 0, errz.Err(err)

View File

@ -30,7 +30,7 @@ const typeTestTableDDLPath = "testdata/type_test.ddl"
// - Row 1 contains non-zero values. // - Row 1 contains non-zero values.
// - Row 2 contains non-zero values and nil values for cols that permit // - Row 2 contains non-zero values and nil values for cols that permit
// nil values (those cols ending with _n such as col_text_n). // nil values (those cols ending with _n such as col_text_n).
var typeTestVals = [][]interface{}{ var typeTestVals = [][]any{
{ {
1, // col_id 1, // col_id
fixt.IntZ, // col_bigint fixt.IntZ, // col_bigint

View File

@ -228,7 +228,7 @@ func (d *driveri) RecordMeta(colTypes []*sql.ColumnType) (sqlz.RecordMeta, drive
recMeta[i] = sqlz.NewFieldMeta(colTypeData) recMeta[i] = sqlz.NewFieldMeta(colTypeData)
} }
mungeFn := func(vals []interface{}) (sqlz.Record, error) { mungeFn := func(vals []any) (sqlz.Record, error) {
// sqlserver doesn't need to do any special munging, so we // sqlserver doesn't need to do any special munging, so we
// just use the default munging. // just use the default munging.
rec, skipped := driver.NewRecordFromScanRow(recMeta, vals, nil) rec, skipped := driver.NewRecordFromScanRow(recMeta, vals, nil)
@ -449,7 +449,7 @@ func (d *database) Close() error {
// the "identity insert" error. If the error is encountered, setIdentityInsert // the "identity insert" error. If the error is encountered, setIdentityInsert
// is called and stmt is executed again. // is called and stmt is executed again.
func newStmtExecFunc(stmt *sql.Stmt, db sqlz.DB, tbl string) driver.StmtExecFunc { func newStmtExecFunc(stmt *sql.Stmt, db sqlz.DB, tbl string) driver.StmtExecFunc {
return func(ctx context.Context, args ...interface{}) (int64, error) { return func(ctx context.Context, args ...any) (int64, error) {
res, err := stmt.ExecContext(ctx, args...) res, err := stmt.ExecContext(ctx, args...)
if err == nil { if err == nil {
var affected int64 var affected int64

View File

@ -12,8 +12,8 @@ import (
type rowState struct { type rowState struct {
tbl *userdriver.TableMapping tbl *userdriver.TableMapping
dirtyColVals map[string]interface{} dirtyColVals map[string]any
savedColVals map[string]interface{} savedColVals map[string]any
curCol *userdriver.ColMapping curCol *userdriver.ColMapping
} }

View File

@ -37,8 +37,8 @@ func Import(ctx context.Context, log lg.Log, def *userdriver.DriverDef, data io.
rowStack: newRowStack(), rowStack: newRowStack(),
tblDefs: map[string]*sqlmodel.TableDef{}, tblDefs: map[string]*sqlmodel.TableDef{},
tblSequence: map[string]int64{}, tblSequence: map[string]int64{},
execInsertFns: map[string]func(ctx context.Context, insertVals []interface{}) error{}, execInsertFns: map[string]func(ctx context.Context, insertVals []any) error{},
execUpdateFns: map[string]func(ctx context.Context, updateVals []interface{}, whereArgs []interface{}) error{}, execUpdateFns: map[string]func(ctx context.Context, updateVals []any, whereArgs []any) error{},
clnup: cleanup.New(), clnup: cleanup.New(),
msgOnce: map[string]struct{}{}, msgOnce: map[string]struct{}{},
} }
@ -69,12 +69,12 @@ type importer struct {
// execInsertFns is a map of a table+cols key to an func for inserting // execInsertFns is a map of a table+cols key to an func for inserting
// vals. Effectively it can be considered a cache of prepared insert // vals. Effectively it can be considered a cache of prepared insert
// statements. See the dbInsert function. // statements. See the dbInsert function.
execInsertFns map[string]func(ctx context.Context, vals []interface{}) error execInsertFns map[string]func(ctx context.Context, vals []any) error
// execUpdateFns is similar to execInsertFns, but for UPDATE instead // execUpdateFns is similar to execInsertFns, but for UPDATE instead
// of INSERT. The whereArgs param is the arguments for the // of INSERT. The whereArgs param is the arguments for the
// update's WHERE clause. // update's WHERE clause.
execUpdateFns map[string]func(ctx context.Context, updateVals []interface{}, whereArgs []interface{}) error execUpdateFns map[string]func(ctx context.Context, updateVals []any, whereArgs []any) error
// clnup holds cleanup funcs that should be run when the importer // clnup holds cleanup funcs that should be run when the importer
// finishes. // finishes.
@ -197,7 +197,7 @@ func (im *importer) execImport(ctx context.Context, r io.Reader, destDB driver.D
return nil return nil
} }
func (im *importer) convertVal(tbl string, col *userdriver.ColMapping, data interface{}) (interface{}, error) { func (im *importer) convertVal(tbl string, col *userdriver.ColMapping, data any) (any, error) {
const errTpl = `conversion error: %s.%s: expected "%s" but got %T(%v)` const errTpl = `conversion error: %s.%s: expected "%s" but got %T(%v)`
const errTplMsg = `conversion error: %s.%s: expected "%s" but got %T(%v): %v` const errTplMsg = `conversion error: %s.%s: expected "%s" but got %T(%v): %v`
@ -411,7 +411,7 @@ func (im *importer) saveRow(ctx context.Context, row *rowState) error {
func (im *importer) dbInsert(ctx context.Context, row *rowState) error { func (im *importer) dbInsert(ctx context.Context, row *rowState) error {
tblName := row.tbl.Name tblName := row.tbl.Name
colNames := make([]string, len(row.dirtyColVals)) colNames := make([]string, len(row.dirtyColVals))
vals := make([]interface{}, len(row.dirtyColVals)) vals := make([]any, len(row.dirtyColVals))
i := 0 i := 0
for k, v := range row.dirtyColVals { for k, v := range row.dirtyColVals {
@ -433,7 +433,7 @@ func (im *importer) dbInsert(ctx context.Context, row *rowState) error {
// Make sure we close stmt eventually. // Make sure we close stmt eventually.
im.clnup.AddC(stmtExecer) im.clnup.AddC(stmtExecer)
execInsertFn = func(ctx context.Context, vals []interface{}) error { execInsertFn = func(ctx context.Context, vals []any) error {
// Munge vals so that they're as the target DB expects // Munge vals so that they're as the target DB expects
err = stmtExecer.Munge(vals) err = stmtExecer.Munge(vals)
if err != nil { if err != nil {
@ -464,7 +464,7 @@ func (im *importer) dbUpdate(ctx context.Context, row *rowState) error {
pkColNames := row.tbl.PrimaryKey pkColNames := row.tbl.PrimaryKey
var whereBuilder strings.Builder var whereBuilder strings.Builder
var pkVals []interface{} var pkVals []any
for i, pkColName := range pkColNames { for i, pkColName := range pkColNames {
if pkVal, ok := row.savedColVals[pkColName]; ok { if pkVal, ok := row.savedColVals[pkColName]; ok {
pkVals = append(pkVals, pkVal) pkVals = append(pkVals, pkVal)
@ -484,7 +484,7 @@ func (im *importer) dbUpdate(ctx context.Context, row *rowState) error {
whereClause := whereBuilder.String() whereClause := whereBuilder.String()
colNames := make([]string, len(row.dirtyColVals)) colNames := make([]string, len(row.dirtyColVals))
dirtyVals := make([]interface{}, len(row.dirtyColVals)) dirtyVals := make([]any, len(row.dirtyColVals))
i := 0 i := 0
for k, v := range row.dirtyColVals { for k, v := range row.dirtyColVals {
@ -505,7 +505,7 @@ func (im *importer) dbUpdate(ctx context.Context, row *rowState) error {
// Make sure we close stmt eventually. // Make sure we close stmt eventually.
im.clnup.AddC(stmtExecer) im.clnup.AddC(stmtExecer)
execUpdateFn = func(ctx context.Context, updateVals []interface{}, whereArgs []interface{}) error { execUpdateFn = func(ctx context.Context, updateVals []any, whereArgs []any) error {
// Munge vals so that they're as the target DB expects // Munge vals so that they're as the target DB expects
err := stmtExecer.Munge(updateVals) err := stmtExecer.Munge(updateVals)
if err != nil { if err != nil {
@ -537,8 +537,8 @@ func (im *importer) buildRow() (*rowState, error) {
} }
r := &rowState{tbl: tbl} r := &rowState{tbl: tbl}
r.dirtyColVals = make(map[string]interface{}) r.dirtyColVals = make(map[string]any)
r.savedColVals = make(map[string]interface{}) r.savedColVals = make(map[string]any)
for i := range r.tbl.Cols { for i := range r.tbl.Cols {
// If the table has a column that has a "text()" selector, then we need to capture the // If the table has a column that has a "text()" selector, then we need to capture the
@ -585,7 +585,7 @@ func (im *importer) isRowSelector() bool {
// msgOncef is used to prevent repeated logging of a message. The // msgOncef is used to prevent repeated logging of a message. The
// method returns ok=true and the formatted string if the formatted // method returns ok=true and the formatted string if the formatted
// string has not been previous seen by msgOncef. // string has not been previous seen by msgOncef.
func (im *importer) msgOncef(format string, a ...interface{}) (msg string, ok bool) { func (im *importer) msgOncef(format string, a ...any) (msg string, ok bool) {
msg = fmt.Sprintf(format, a...) msg = fmt.Sprintf(format, a...)
if _, exists := im.msgOnce[msg]; exists { if _, exists := im.msgOnce[msg]; exists {

View File

@ -297,8 +297,8 @@ func syncColNamesKinds(colNames []string, colKinds []kind.Kind) (names []string,
return colNames, colKinds return colNames, colKinds
} }
func rowToRecord(log lg.Log, destColKinds []kind.Kind, row *xlsx.Row, sheetName string, rowIndex int) []interface{} { func rowToRecord(log lg.Log, destColKinds []kind.Kind, row *xlsx.Row, sheetName string, rowIndex int) []any {
vals := make([]interface{}, len(destColKinds)) vals := make([]any, len(destColKinds))
for j, cell := range row.Cells { for j, cell := range row.Cells {
if j >= len(vals) { if j >= len(vals) {
log.Warnf("sheet %s[%d:%d]: skipping additional cells because there's more cells than expected (%d)", log.Warnf("sheet %s[%d:%d]: skipping additional cells because there's more cells than expected (%d)",
@ -369,12 +369,12 @@ func rowToRecord(log lg.Log, destColKinds []kind.Kind, row *xlsx.Row, sheetName
// readCellValue reads the value of a cell, returning a value of // readCellValue reads the value of a cell, returning a value of
// type that most matches the sq kind. // type that most matches the sq kind.
func readCellValue(cell *xlsx.Cell) interface{} { func readCellValue(cell *xlsx.Cell) any {
if cell == nil || cell.Value == "" { if cell == nil || cell.Value == "" {
return nil return nil
} }
var val interface{} var val any
switch cell.Type() { switch cell.Type() {
case xlsx.CellTypeBool: case xlsx.CellTypeBool:

View File

@ -160,6 +160,6 @@ func (a *AST) AddSegment(seg *Segment) {
// errorf builds an error. Error creation for this package // errorf builds an error. Error creation for this package
// was centralized here in the expectation that an AST-specific // was centralized here in the expectation that an AST-specific
// error type (annotated appropriately) would be returned. // error type (annotated appropriately) would be returned.
func errorf(format string, v ...interface{}) error { func errorf(format string, v ...any) error {
return errz.Errorf(format, v...) return errz.Errorf(format, v...)
} }

View File

@ -7,70 +7,70 @@ type BaseSLQVisitor struct {
*antlr.BaseParseTreeVisitor *antlr.BaseParseTreeVisitor
} }
func (v *BaseSLQVisitor) VisitStmtList(ctx *StmtListContext) interface{} { func (v *BaseSLQVisitor) VisitStmtList(ctx *StmtListContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitQuery(ctx *QueryContext) interface{} { func (v *BaseSLQVisitor) VisitQuery(ctx *QueryContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitSegment(ctx *SegmentContext) interface{} { func (v *BaseSLQVisitor) VisitSegment(ctx *SegmentContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitElement(ctx *ElementContext) interface{} { func (v *BaseSLQVisitor) VisitElement(ctx *ElementContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitCmpr(ctx *CmprContext) interface{} { func (v *BaseSLQVisitor) VisitCmpr(ctx *CmprContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitFn(ctx *FnContext) interface{} { func (v *BaseSLQVisitor) VisitFn(ctx *FnContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitJoin(ctx *JoinContext) interface{} { func (v *BaseSLQVisitor) VisitJoin(ctx *JoinContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitJoinConstraint(ctx *JoinConstraintContext) interface{} { func (v *BaseSLQVisitor) VisitJoinConstraint(ctx *JoinConstraintContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitGroup(ctx *GroupContext) interface{} { func (v *BaseSLQVisitor) VisitGroup(ctx *GroupContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitSelElement(ctx *SelElementContext) interface{} { func (v *BaseSLQVisitor) VisitSelElement(ctx *SelElementContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitDsTblElement(ctx *DsTblElementContext) interface{} { func (v *BaseSLQVisitor) VisitDsTblElement(ctx *DsTblElementContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitDsElement(ctx *DsElementContext) interface{} { func (v *BaseSLQVisitor) VisitDsElement(ctx *DsElementContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitRowRange(ctx *RowRangeContext) interface{} { func (v *BaseSLQVisitor) VisitRowRange(ctx *RowRangeContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitFnName(ctx *FnNameContext) interface{} { func (v *BaseSLQVisitor) VisitFnName(ctx *FnNameContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitExpr(ctx *ExprContext) interface{} { func (v *BaseSLQVisitor) VisitExpr(ctx *ExprContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitLiteral(ctx *LiteralContext) interface{} { func (v *BaseSLQVisitor) VisitLiteral(ctx *LiteralContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
func (v *BaseSLQVisitor) VisitUnaryOperator(ctx *UnaryOperatorContext) interface{} { func (v *BaseSLQVisitor) VisitUnaryOperator(ctx *UnaryOperatorContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }

View File

@ -308,7 +308,7 @@ func (s *StmtListContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *StmtListContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *StmtListContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitStmtList(s) return t.VisitStmtList(s)
@ -497,7 +497,7 @@ func (s *QueryContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *QueryContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *QueryContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitQuery(s) return t.VisitQuery(s)
@ -644,7 +644,7 @@ func (s *SegmentContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *SegmentContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *SegmentContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitSegment(s) return t.VisitSegment(s)
@ -841,7 +841,7 @@ func (s *ElementContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *ElementContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *ElementContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitElement(s) return t.VisitElement(s)
@ -1017,7 +1017,7 @@ func (s *CmprContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *CmprContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *CmprContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitCmpr(s) return t.VisitCmpr(s)
@ -1171,7 +1171,7 @@ func (s *FnContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *FnContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *FnContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitFn(s) return t.VisitFn(s)
@ -1333,7 +1333,7 @@ func (s *JoinContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *JoinContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *JoinContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitJoin(s) return t.VisitJoin(s)
@ -1468,7 +1468,7 @@ func (s *JoinConstraintContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *JoinConstraintContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *JoinConstraintContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitJoinConstraint(s) return t.VisitJoinConstraint(s)
@ -1610,7 +1610,7 @@ func (s *GroupContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *GroupContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *GroupContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitGroup(s) return t.VisitGroup(s)
@ -1749,7 +1749,7 @@ func (s *SelElementContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *SelElementContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *SelElementContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitSelElement(s) return t.VisitSelElement(s)
@ -1854,7 +1854,7 @@ func (s *DsTblElementContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *DsTblElementContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *DsTblElementContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitDsTblElement(s) return t.VisitDsTblElement(s)
@ -1959,7 +1959,7 @@ func (s *DsElementContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *DsElementContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *DsElementContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitDsElement(s) return t.VisitDsElement(s)
@ -2072,7 +2072,7 @@ func (s *RowRangeContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *RowRangeContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *RowRangeContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitRowRange(s) return t.VisitRowRange(s)
@ -2216,7 +2216,7 @@ func (s *FnNameContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *FnNameContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *FnNameContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitFnName(s) return t.VisitFnName(s)
@ -2402,7 +2402,7 @@ func (s *ExprContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *ExprContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *ExprContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitExpr(s) return t.VisitExpr(s)
@ -2743,7 +2743,7 @@ func (s *LiteralContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *LiteralContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *LiteralContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitLiteral(s) return t.VisitLiteral(s)
@ -2847,7 +2847,7 @@ func (s *UnaryOperatorContext) ExitRule(listener antlr.ParseTreeListener) {
} }
} }
func (s *UnaryOperatorContext) Accept(visitor antlr.ParseTreeVisitor) interface{} { func (s *UnaryOperatorContext) Accept(visitor antlr.ParseTreeVisitor) any {
switch t := visitor.(type) { switch t := visitor.(type) {
case SLQVisitor: case SLQVisitor:
return t.VisitUnaryOperator(s) return t.VisitUnaryOperator(s)

View File

@ -8,53 +8,53 @@ type SLQVisitor interface {
antlr.ParseTreeVisitor antlr.ParseTreeVisitor
// Visit a parse tree produced by SLQParser#stmtList. // Visit a parse tree produced by SLQParser#stmtList.
VisitStmtList(ctx *StmtListContext) interface{} VisitStmtList(ctx *StmtListContext) any
// Visit a parse tree produced by SLQParser#query. // Visit a parse tree produced by SLQParser#query.
VisitQuery(ctx *QueryContext) interface{} VisitQuery(ctx *QueryContext) any
// Visit a parse tree produced by SLQParser#segment. // Visit a parse tree produced by SLQParser#segment.
VisitSegment(ctx *SegmentContext) interface{} VisitSegment(ctx *SegmentContext) any
// Visit a parse tree produced by SLQParser#element. // Visit a parse tree produced by SLQParser#element.
VisitElement(ctx *ElementContext) interface{} VisitElement(ctx *ElementContext) any
// Visit a parse tree produced by SLQParser#cmpr. // Visit a parse tree produced by SLQParser#cmpr.
VisitCmpr(ctx *CmprContext) interface{} VisitCmpr(ctx *CmprContext) any
// Visit a parse tree produced by SLQParser#fn. // Visit a parse tree produced by SLQParser#fn.
VisitFn(ctx *FnContext) interface{} VisitFn(ctx *FnContext) any
// Visit a parse tree produced by SLQParser#join. // Visit a parse tree produced by SLQParser#join.
VisitJoin(ctx *JoinContext) interface{} VisitJoin(ctx *JoinContext) any
// Visit a parse tree produced by SLQParser#joinConstraint. // Visit a parse tree produced by SLQParser#joinConstraint.
VisitJoinConstraint(ctx *JoinConstraintContext) interface{} VisitJoinConstraint(ctx *JoinConstraintContext) any
// Visit a parse tree produced by SLQParser#group. // Visit a parse tree produced by SLQParser#group.
VisitGroup(ctx *GroupContext) interface{} VisitGroup(ctx *GroupContext) any
// Visit a parse tree produced by SLQParser#selElement. // Visit a parse tree produced by SLQParser#selElement.
VisitSelElement(ctx *SelElementContext) interface{} VisitSelElement(ctx *SelElementContext) any
// Visit a parse tree produced by SLQParser#dsTblElement. // Visit a parse tree produced by SLQParser#dsTblElement.
VisitDsTblElement(ctx *DsTblElementContext) interface{} VisitDsTblElement(ctx *DsTblElementContext) any
// Visit a parse tree produced by SLQParser#dsElement. // Visit a parse tree produced by SLQParser#dsElement.
VisitDsElement(ctx *DsElementContext) interface{} VisitDsElement(ctx *DsElementContext) any
// Visit a parse tree produced by SLQParser#rowRange. // Visit a parse tree produced by SLQParser#rowRange.
VisitRowRange(ctx *RowRangeContext) interface{} VisitRowRange(ctx *RowRangeContext) any
// Visit a parse tree produced by SLQParser#fnName. // Visit a parse tree produced by SLQParser#fnName.
VisitFnName(ctx *FnNameContext) interface{} VisitFnName(ctx *FnNameContext) any
// Visit a parse tree produced by SLQParser#expr. // Visit a parse tree produced by SLQParser#expr.
VisitExpr(ctx *ExprContext) interface{} VisitExpr(ctx *ExprContext) any
// Visit a parse tree produced by SLQParser#literal. // Visit a parse tree produced by SLQParser#literal.
VisitLiteral(ctx *LiteralContext) interface{} VisitLiteral(ctx *LiteralContext) any
// Visit a parse tree produced by SLQParser#unaryOperator. // Visit a parse tree produced by SLQParser#unaryOperator.
VisitUnaryOperator(ctx *UnaryOperatorContext) interface{} VisitUnaryOperator(ctx *UnaryOperatorContext) any
} }

View File

@ -67,7 +67,7 @@ func (el *antlrErrorListener) String() string {
} }
// SyntaxError implements antlr.ErrorListener. // SyntaxError implements antlr.ErrorListener.
func (el *antlrErrorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) { func (el *antlrErrorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, e antlr.RecognitionException) {
text := fmt.Sprintf("%s: syntax error: [%d:%d] %s", el.name, line, column, msg) text := fmt.Sprintf("%s: syntax error: [%d:%d] %s", el.name, line, column, msg)
el.errs = append(el.errs, text) el.errs = append(el.errs, text)
} }
@ -117,7 +117,7 @@ type parseTreeVisitor struct {
} }
// Visit implements antlr.ParseTreeVisitor. // Visit implements antlr.ParseTreeVisitor.
func (v *parseTreeVisitor) Visit(ctx antlr.ParseTree) interface{} { func (v *parseTreeVisitor) Visit(ctx antlr.ParseTree) any {
v.log.Debugf("visiting %T: %v: ", ctx, ctx.GetText()) v.log.Debugf("visiting %T: %v: ", ctx, ctx.GetText())
switch ctx := ctx.(type) { switch ctx := ctx.(type) {
@ -158,7 +158,7 @@ func (v *parseTreeVisitor) Visit(ctx antlr.ParseTree) interface{} {
} }
// VisitChildren implements antlr.ParseTreeVisitor. // VisitChildren implements antlr.ParseTreeVisitor.
func (v *parseTreeVisitor) VisitChildren(ctx antlr.RuleNode) interface{} { func (v *parseTreeVisitor) VisitChildren(ctx antlr.RuleNode) any {
for _, child := range ctx.GetChildren() { for _, child := range ctx.GetChildren() {
tree, ok := child.(antlr.ParseTree) tree, ok := child.(antlr.ParseTree)
if !ok { if !ok {
@ -174,7 +174,7 @@ func (v *parseTreeVisitor) VisitChildren(ctx antlr.RuleNode) interface{} {
} }
// VisitQuery implements slq.SLQVisitor. // VisitQuery implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitQuery(ctx *slq.QueryContext) interface{} { func (v *parseTreeVisitor) VisitQuery(ctx *slq.QueryContext) any {
v.AST = &AST{} v.AST = &AST{}
v.AST.ctx = ctx v.AST.ctx = ctx
v.cur = v.AST v.cur = v.AST
@ -190,7 +190,7 @@ func (v *parseTreeVisitor) VisitQuery(ctx *slq.QueryContext) interface{} {
} }
// VisitDsElement implements slq.SLQVisitor. // VisitDsElement implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitDsElement(ctx *slq.DsElementContext) interface{} { func (v *parseTreeVisitor) VisitDsElement(ctx *slq.DsElementContext) any {
ds := &Datasource{} ds := &Datasource{}
ds.parent = v.cur ds.parent = v.cur
ds.ctx = ctx.DATASOURCE() ds.ctx = ctx.DATASOURCE()
@ -198,7 +198,7 @@ func (v *parseTreeVisitor) VisitDsElement(ctx *slq.DsElementContext) interface{}
} }
// VisitDsTblElement implements slq.SLQVisitor. // VisitDsTblElement implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitDsTblElement(ctx *slq.DsTblElementContext) interface{} { func (v *parseTreeVisitor) VisitDsTblElement(ctx *slq.DsTblElementContext) any {
tblSel := &TblSelector{} tblSel := &TblSelector{}
tblSel.parent = v.cur tblSel.parent = v.cur
tblSel.ctx = ctx tblSel.ctx = ctx
@ -210,7 +210,7 @@ func (v *parseTreeVisitor) VisitDsTblElement(ctx *slq.DsTblElementContext) inter
} }
// VisitSegment implements slq.SLQVisitor. // VisitSegment implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitSegment(ctx *slq.SegmentContext) interface{} { func (v *parseTreeVisitor) VisitSegment(ctx *slq.SegmentContext) any {
seg := &Segment{} seg := &Segment{}
seg.bn.ctx = ctx seg.bn.ctx = ctx
seg.bn.parent = v.AST seg.bn.parent = v.AST
@ -222,7 +222,7 @@ func (v *parseTreeVisitor) VisitSegment(ctx *slq.SegmentContext) interface{} {
} }
// VisitSelElement implements slq.SLQVisitor. // VisitSelElement implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitSelElement(ctx *slq.SelElementContext) interface{} { func (v *parseTreeVisitor) VisitSelElement(ctx *slq.SelElementContext) any {
selector := &Selector{} selector := &Selector{}
selector.parent = v.cur selector.parent = v.cur
selector.ctx = ctx.SEL() selector.ctx = ctx.SEL()
@ -230,12 +230,12 @@ func (v *parseTreeVisitor) VisitSelElement(ctx *slq.SelElementContext) interface
} }
// VisitElement implements slq.SLQVisitor. // VisitElement implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitElement(ctx *slq.ElementContext) interface{} { func (v *parseTreeVisitor) VisitElement(ctx *slq.ElementContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
// VisitFn implements slq.SLQVisitor. // VisitFn implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitFn(ctx *slq.FnContext) interface{} { func (v *parseTreeVisitor) VisitFn(ctx *slq.FnContext) any {
v.log.Debugf("visiting function: %v", ctx.GetText()) v.log.Debugf("visiting function: %v", ctx.GetText())
fn := &Func{fnName: ctx.FnName().GetText()} fn := &Func{fnName: ctx.FnName().GetText()}
@ -257,7 +257,7 @@ func (v *parseTreeVisitor) VisitFn(ctx *slq.FnContext) interface{} {
} }
// VisitExpr implements slq.SLQVisitor. // VisitExpr implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitExpr(ctx *slq.ExprContext) interface{} { func (v *parseTreeVisitor) VisitExpr(ctx *slq.ExprContext) any {
v.log.Debugf("visiting expr: %v", ctx.GetText()) v.log.Debugf("visiting expr: %v", ctx.GetText())
// check if the expr is a SEL, e.g. ".uid" // check if the expr is a SEL, e.g. ".uid"
@ -292,17 +292,17 @@ func (v *parseTreeVisitor) VisitExpr(ctx *slq.ExprContext) interface{} {
} }
// VisitCmpr implements slq.SLQVisitor. // VisitCmpr implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitCmpr(ctx *slq.CmprContext) interface{} { func (v *parseTreeVisitor) VisitCmpr(ctx *slq.CmprContext) any {
return v.VisitChildren(ctx) return v.VisitChildren(ctx)
} }
// VisitStmtList implements slq.SLQVisitor. // VisitStmtList implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitStmtList(ctx *slq.StmtListContext) interface{} { func (v *parseTreeVisitor) VisitStmtList(ctx *slq.StmtListContext) any {
return nil // not using StmtList just yet return nil // not using StmtList just yet
} }
// VisitLiteral implements slq.SLQVisitor. // VisitLiteral implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitLiteral(ctx *slq.LiteralContext) interface{} { func (v *parseTreeVisitor) VisitLiteral(ctx *slq.LiteralContext) any {
v.log.Debugf("visiting literal: %q", ctx.GetText()) v.log.Debugf("visiting literal: %q", ctx.GetText())
lit := &Literal{} lit := &Literal{}
@ -313,17 +313,17 @@ func (v *parseTreeVisitor) VisitLiteral(ctx *slq.LiteralContext) interface{} {
} }
// VisitUnaryOperator implements slq.SLQVisitor. // VisitUnaryOperator implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitUnaryOperator(ctx *slq.UnaryOperatorContext) interface{} { func (v *parseTreeVisitor) VisitUnaryOperator(ctx *slq.UnaryOperatorContext) any {
return nil return nil
} }
// VisitFnName implements slq.SLQVisitor. // VisitFnName implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitFnName(ctx *slq.FnNameContext) interface{} { func (v *parseTreeVisitor) VisitFnName(ctx *slq.FnNameContext) any {
return nil return nil
} }
// VisitGroup implements slq.SLQVisitor. // VisitGroup implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitGroup(ctx *slq.GroupContext) interface{} { func (v *parseTreeVisitor) VisitGroup(ctx *slq.GroupContext) any {
// parent node must be a segment // parent node must be a segment
_, ok := v.cur.(*Segment) _, ok := v.cur.(*Segment)
if !ok { if !ok {
@ -353,7 +353,7 @@ func (v *parseTreeVisitor) VisitGroup(ctx *slq.GroupContext) interface{} {
} }
// VisitJoin implements slq.SLQVisitor. // VisitJoin implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitJoin(ctx *slq.JoinContext) interface{} { func (v *parseTreeVisitor) VisitJoin(ctx *slq.JoinContext) any {
// parent node must be a segment // parent node must be a segment
seg, ok := v.cur.(*Segment) seg, ok := v.cur.(*Segment)
if !ok { if !ok {
@ -383,7 +383,7 @@ func (v *parseTreeVisitor) VisitJoin(ctx *slq.JoinContext) interface{} {
} }
// VisitJoinConstraint implements slq.SLQVisitor. // VisitJoinConstraint implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitJoinConstraint(ctx *slq.JoinConstraintContext) interface{} { func (v *parseTreeVisitor) VisitJoinConstraint(ctx *slq.JoinConstraintContext) any {
joinNode, ok := v.cur.(*Join) joinNode, ok := v.cur.(*Join)
if !ok { if !ok {
return errorf("JOIN constraint must have JOIN parent, but got %T", v.cur) return errorf("JOIN constraint must have JOIN parent, but got %T", v.cur)
@ -455,7 +455,7 @@ func (v *parseTreeVisitor) VisitJoinConstraint(ctx *slq.JoinConstraintContext) i
} }
// VisitTerminal implements slq.SLQVisitor. // VisitTerminal implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitTerminal(ctx antlr.TerminalNode) interface{} { func (v *parseTreeVisitor) VisitTerminal(ctx antlr.TerminalNode) any {
v.log.Debugf("visiting terminal: %q", ctx.GetText()) v.log.Debugf("visiting terminal: %q", ctx.GetText())
val := ctx.GetText() val := ctx.GetText()
@ -482,7 +482,7 @@ func (v *parseTreeVisitor) VisitTerminal(ctx antlr.TerminalNode) interface{} {
} }
// VisitRowRange implements slq.SLQVisitor. // VisitRowRange implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitRowRange(ctx *slq.RowRangeContext) interface{} { func (v *parseTreeVisitor) VisitRowRange(ctx *slq.RowRangeContext) any {
// [] select all rows (no range) // [] select all rows (no range)
// [1] select row[1] // [1] select row[1]
// [10:15] select rows 10 thru 15 // [10:15] select rows 10 thru 15
@ -541,7 +541,7 @@ func (v *parseTreeVisitor) VisitRowRange(ctx *slq.RowRangeContext) interface{} {
} }
// VisitErrorNode implements slq.SLQVisitor. // VisitErrorNode implements slq.SLQVisitor.
func (v *parseTreeVisitor) VisitErrorNode(ctx antlr.ErrorNode) interface{} { func (v *parseTreeVisitor) VisitErrorNode(ctx antlr.ErrorNode) any {
v.log.Debugf("error node: %v", ctx.GetText()) v.log.Debugf("error node: %v", ctx.GetText())
return nil return nil
} }

View File

@ -16,7 +16,7 @@ type Walker struct {
visitors map[reflect.Type][]nodeVisitorFn visitors map[reflect.Type][]nodeVisitorFn
// state is a generic field to hold any data that a visitor function // state is a generic field to hold any data that a visitor function
// might need to stash on the walker. // might need to stash on the walker.
state interface{} state any
} }
// NewWalker returns a new Walker instance. // NewWalker returns a new Walker instance.

View File

@ -159,7 +159,7 @@ type Detector struct {
// MungeFunc is a function that accepts a value and returns a munged // MungeFunc is a function that accepts a value and returns a munged
// value with the appropriate Kind. For example, a Datetime MungeFunc // value with the appropriate Kind. For example, a Datetime MungeFunc
// would accept string "2020-06-11T02:50:54Z" and return a time.Time, // would accept string "2020-06-11T02:50:54Z" and return a time.Time,
type MungeFunc func(interface{}) (interface{}, error) type MungeFunc func(any) (any, error)
// NewDetector returns a new instance. // NewDetector returns a new instance.
func NewDetector() *Detector { func NewDetector() *Detector {
@ -178,7 +178,7 @@ func NewDetector() *Detector {
} }
// Sample adds a sample to the detector. // Sample adds a sample to the detector.
func (d *Detector) Sample(v interface{}) { func (d *Detector) Sample(v any) {
switch v.(type) { switch v.(type) {
case nil: case nil:
// Can't glean any info from nil // Can't glean any info from nil
@ -273,7 +273,7 @@ func (d *Detector) doSampleString(s string) {
// If it's kind.Time, it can't be anything else // If it's kind.Time, it can't be anything else
d.retain(Time) d.retain(Time)
d.mungeFns[Time] = func(val interface{}) (interface{}, error) { d.mungeFns[Time] = func(val any) (any, error) {
if val == nil { if val == nil {
return nil, nil return nil, nil
} }
@ -307,7 +307,7 @@ func (d *Detector) doSampleString(s string) {
// If it's kind.Date, it can't be anything else // If it's kind.Date, it can't be anything else
d.retain(Date) d.retain(Date)
d.mungeFns[Date] = func(val interface{}) (interface{}, error) { d.mungeFns[Date] = func(val any) (any, error) {
if val == nil { if val == nil {
return nil, nil return nil, nil
} }
@ -343,7 +343,7 @@ func (d *Detector) doSampleString(s string) {
// This mungeFn differs from kind.Date and kind.Time in that // This mungeFn differs from kind.Date and kind.Time in that
// it returns a time.Time instead of a string // it returns a time.Time instead of a string
d.mungeFns[Datetime] = func(val interface{}) (interface{}, error) { d.mungeFns[Datetime] = func(val any) (any, error) {
if val == nil { if val == nil {
return nil, nil return nil, nil
} }

View File

@ -83,50 +83,50 @@ func TestKindDetector(t *testing.T) {
) )
testCases := []struct { testCases := []struct {
in []interface{} in []any
want kind.Kind want kind.Kind
wantMunge bool wantMunge bool
wantErr bool wantErr bool
}{ }{
{in: nil, want: kind.Null}, {in: nil, want: kind.Null},
{in: []interface{}{}, want: kind.Null}, {in: []any{}, want: kind.Null},
{in: []interface{}{""}, want: kind.Text}, {in: []any{""}, want: kind.Text},
{in: []interface{}{nil}, want: kind.Null}, {in: []any{nil}, want: kind.Null},
{in: []interface{}{nil, ""}, want: kind.Text}, {in: []any{nil, ""}, want: kind.Text},
{in: []interface{}{int(1), int8(8), int16(16), int32(32), int64(64)}, want: kind.Int}, {in: []any{int(1), int8(8), int16(16), int32(32), int64(64)}, want: kind.Int},
{in: []interface{}{1, "2", "3"}, want: kind.Decimal}, {in: []any{1, "2", "3"}, want: kind.Decimal},
{in: []interface{}{"99999999999999999999999999999999999999999999999999999999"}, want: kind.Decimal}, {in: []any{"99999999999999999999999999999999999999999999999999999999"}, want: kind.Decimal},
{in: []interface{}{"99999999999999999999999999999999999999999999999999999999xxx"}, want: kind.Text}, {in: []any{"99999999999999999999999999999999999999999999999999999999xxx"}, want: kind.Text},
{in: []interface{}{1, "2", stdj.Number("1000")}, want: kind.Decimal}, {in: []any{1, "2", stdj.Number("1000")}, want: kind.Decimal},
{in: []interface{}{1.0, "2.0"}, want: kind.Decimal}, {in: []any{1.0, "2.0"}, want: kind.Decimal},
{in: []interface{}{1, float64(2.0), float32(7.7), int32(3)}, want: kind.Float}, {in: []any{1, float64(2.0), float32(7.7), int32(3)}, want: kind.Float},
{in: []interface{}{nil, nil, nil}, want: kind.Null}, {in: []any{nil, nil, nil}, want: kind.Null},
{in: []interface{}{"1.0", "2.0", "3.0", "4", nil, int64(6)}, want: kind.Decimal}, {in: []any{"1.0", "2.0", "3.0", "4", nil, int64(6)}, want: kind.Decimal},
{in: []interface{}{true, false, nil, "true", "false", "yes", "no", ""}, want: kind.Bool}, {in: []any{true, false, nil, "true", "false", "yes", "no", ""}, want: kind.Bool},
{in: []interface{}{"0", "1"}, want: kind.Decimal}, {in: []any{"0", "1"}, want: kind.Decimal},
{in: []interface{}{fixtTime1, nil, ""}, want: kind.Time, wantMunge: true}, {in: []any{fixtTime1, nil, ""}, want: kind.Time, wantMunge: true},
{in: []interface{}{fixtTime2}, want: kind.Time, wantMunge: true}, {in: []any{fixtTime2}, want: kind.Time, wantMunge: true},
{in: []interface{}{fixtTime3}, want: kind.Time, wantMunge: true}, {in: []any{fixtTime3}, want: kind.Time, wantMunge: true},
{in: []interface{}{fixtTime4}, want: kind.Time, wantMunge: true}, {in: []any{fixtTime4}, want: kind.Time, wantMunge: true},
{in: []interface{}{fixtDate1, nil, ""}, want: kind.Date, wantMunge: true}, {in: []any{fixtDate1, nil, ""}, want: kind.Date, wantMunge: true},
{in: []interface{}{fixtDate2}, want: kind.Date, wantMunge: true}, {in: []any{fixtDate2}, want: kind.Date, wantMunge: true},
{in: []interface{}{fixtDate3}, want: kind.Date, wantMunge: true}, {in: []any{fixtDate3}, want: kind.Date, wantMunge: true},
{in: []interface{}{fixtDate4}, want: kind.Date, wantMunge: true}, {in: []any{fixtDate4}, want: kind.Date, wantMunge: true},
{in: []interface{}{fixtDatetime1, nil, ""}, want: kind.Datetime, wantMunge: true}, {in: []any{fixtDatetime1, nil, ""}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{fixtDatetime2}, want: kind.Datetime, wantMunge: true}, {in: []any{fixtDatetime2}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{fixtDatetimeAnsic}, want: kind.Datetime, wantMunge: true}, {in: []any{fixtDatetimeAnsic}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{fixtDatetimeUnix}, want: kind.Datetime, wantMunge: true}, {in: []any{fixtDatetimeUnix}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{time.RubyDate}, want: kind.Datetime, wantMunge: true}, {in: []any{time.RubyDate}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{time.RFC822}, want: kind.Datetime, wantMunge: true}, {in: []any{time.RFC822}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{time.RFC822Z}, want: kind.Datetime, wantMunge: true}, {in: []any{time.RFC822Z}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{time.RFC850}, want: kind.Datetime, wantMunge: true}, {in: []any{time.RFC850}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{time.RFC1123}, want: kind.Datetime, wantMunge: true}, {in: []any{time.RFC1123}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{time.RFC1123Z}, want: kind.Datetime, wantMunge: true}, {in: []any{time.RFC1123Z}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{fixtDatetimeRFC3339}, want: kind.Datetime, wantMunge: true}, {in: []any{fixtDatetimeRFC3339}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{fixtDatetimeStamp}, want: kind.Datetime, wantMunge: true}, {in: []any{fixtDatetimeStamp}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{fixtDatetimeStampMilli}, want: kind.Datetime, wantMunge: true}, {in: []any{fixtDatetimeStampMilli}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{fixtDatetimeStampMicro}, want: kind.Datetime, wantMunge: true}, {in: []any{fixtDatetimeStampMicro}, want: kind.Datetime, wantMunge: true},
{in: []interface{}{fixtDatetimeStampNano}, want: kind.Datetime, wantMunge: true}, {in: []any{fixtDatetimeStampNano}, want: kind.Datetime, wantMunge: true},
} }
for i, tc := range testCases { for i, tc := range testCases {

View File

@ -13,7 +13,7 @@ type NullBool struct {
} }
// Scan implements the Scanner interface. // Scan implements the Scanner interface.
func (n *NullBool) Scan(value interface{}) error { func (n *NullBool) Scan(value any) error {
if value == nil { if value == nil {
n.Bool, n.Valid = false, false n.Bool, n.Valid = false, false
return nil return nil

View File

@ -10,7 +10,7 @@ import (
func TestNullBool_Scan(t *testing.T) { func TestNullBool_Scan(t *testing.T) {
var tests = []struct { var tests = []struct {
input interface{} input any
expectValid bool expectValid bool
expectBool bool expectBool bool
}{ }{

View File

@ -11,10 +11,10 @@ import (
"github.com/neilotoole/sq/libsq/core/kind" "github.com/neilotoole/sq/libsq/core/kind"
) )
// Record is a []interface{} row of field values returned from a query. // Record is a []any row of field values returned from a query.
// //
// In the codebase, we distinguish between a "Record" and // In the codebase, we distinguish between a "Record" and
// a "ScanRow", although both are []interface{} and are closely related. // a "ScanRow", although both are []any and are closely related.
// //
// An instance of ScanRow is passed to the sql rows.Scan method, and // An instance of ScanRow is passed to the sql rows.Scan method, and
// its elements may include implementations of the sql.Scanner interface // its elements may include implementations of the sql.Scanner interface
@ -26,7 +26,7 @@ import (
// nil, *int64, *float64, *bool, *string, *[]byte, *time.Time // nil, *int64, *float64, *bool, *string, *[]byte, *time.Time
// //
// It is an error for a Record to contain elements of any other type. // It is an error for a Record to contain elements of any other type.
type Record []interface{} type Record []any
// ValidRecord checks that each element of the record vals is // ValidRecord checks that each element of the record vals is
// of an acceptable type. On the first unacceptable element, // of an acceptable type. On the first unacceptable element,
@ -39,7 +39,7 @@ type Record []interface{}
func ValidRecord(recMeta RecordMeta, rec Record) (i int, err error) { func ValidRecord(recMeta RecordMeta, rec Record) (i int, err error) {
// FIXME: ValidRecord should check the values of rec to see if they match recMeta's kinds // FIXME: ValidRecord should check the values of rec to see if they match recMeta's kinds
var val interface{} var val any
for i, val = range rec { for i, val = range rec {
switch val := val.(type) { switch val := val.(type) {
case nil, *int64, *float64, *bool, *string, *[]byte, *time.Time: case nil, *int64, *float64, *bool, *string, *[]byte, *time.Time:
@ -147,10 +147,10 @@ func (rm RecordMeta) Names() []string {
return names return names
} }
// NewScanRow returns a new []interface{} that can be scanned // NewScanRow returns a new []any that can be scanned
// into by sql.Rows.Scan. // into by sql.Rows.Scan.
func (rm RecordMeta) NewScanRow() []interface{} { func (rm RecordMeta) NewScanRow() []any {
dests := make([]interface{}, len(rm)) dests := make([]any, len(rm))
for i, col := range rm { for i, col := range rm {
dests[i] = reflect.New(col.data.ScanType).Interface() dests[i] = reflect.New(col.data.ScanType).Interface()

View File

@ -12,17 +12,17 @@ import (
// from sql.DB and friends. // from sql.DB and friends.
type Execer interface { type Execer interface {
// ExecContext is documented by sql.DB.ExecContext. // ExecContext is documented by sql.DB.ExecContext.
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
} }
// Queryer abstracts the QueryContext and QueryRowContext // Queryer abstracts the QueryContext and QueryRowContext
// methods from sql.DB and friends. // methods from sql.DB and friends.
type Queryer interface { type Queryer interface {
// QueryContext is documented by sql.DB.QueryContext. // QueryContext is documented by sql.DB.QueryContext.
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
// QueryRowContext is documented by sql.DB.QueryRowContext. // QueryRowContext is documented by sql.DB.QueryRowContext.
QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
} }
// Preparer abstracts the PrepareContext method from sql.DB and // Preparer abstracts the PrepareContext method from sql.DB and
@ -44,7 +44,7 @@ type DB interface {
// ExecAffected invokes db.ExecContext, returning the count of rows // ExecAffected invokes db.ExecContext, returning the count of rows
// affected and any error. // affected and any error.
func ExecAffected(ctx context.Context, db Execer, query string, args ...interface{}) (affected int64, err error) { func ExecAffected(ctx context.Context, db Execer, query string, args ...any) (affected int64, err error) {
var res sql.Result var res sql.Result
res, err = db.ExecContext(ctx, query, args...) res, err = db.ExecContext(ctx, query, args...)
if err != nil { if err != nil {

View File

@ -135,7 +135,7 @@ const (
yb yb
) )
func SprintJSON(value interface{}) string { func SprintJSON(value any) string {
j, err := json.MarshalIndent(value, "", " ") j, err := json.MarshalIndent(value, "", " ")
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -203,7 +203,7 @@ func TestSQLDriver_PrepareUpdateStmt(t *testing.T) {
) )
var ( var (
destCols = []string{"first_name", "last_name"} destCols = []string{"first_name", "last_name"}
wantVals = []interface{}{"Kubla", "Khan"} wantVals = []any{"Kubla", "Khan"}
args = append(wantVals, actorID) args = append(wantVals, actorID)
) )

View File

@ -29,7 +29,7 @@ import (
// //
// Thus a func instance might unbox sql.NullString et al, or deal // Thus a func instance might unbox sql.NullString et al, or deal
// with any driver specific quirks. // with any driver specific quirks.
type NewRecordFunc func(scanRow []interface{}) (rec sqlz.Record, err error) type NewRecordFunc func(scanRow []any) (rec sqlz.Record, err error)
// InsertMungeFunc is invoked on vals before insertion (or // InsertMungeFunc is invoked on vals before insertion (or
// update, despite the name). Note that InsertMungeFunc operates // update, despite the name). Note that InsertMungeFunc operates
@ -40,7 +40,7 @@ type InsertMungeFunc func(vals sqlz.Record) error
// execution of a prepared statement. Typically the func will // execution of a prepared statement. Typically the func will
// perform some driver-specific action, such as managing // perform some driver-specific action, such as managing
// retryable errors. // retryable errors.
type StmtExecFunc func(ctx context.Context, args ...interface{}) (affected int64, err error) type StmtExecFunc func(ctx context.Context, args ...any) (affected int64, err error)
// NewStmtExecer returns a new StmtExecer instance. The caller is responsible // NewStmtExecer returns a new StmtExecer instance. The caller is responsible
// for invoking Close on the returned StmtExecer. // for invoking Close on the returned StmtExecer.
@ -72,7 +72,7 @@ func (x *StmtExecer) DestMeta() sqlz.RecordMeta {
// Munge should be applied to each row of values prior // Munge should be applied to each row of values prior
// to inserting invoking Exec. // to inserting invoking Exec.
func (x *StmtExecer) Munge(rec []interface{}) error { func (x *StmtExecer) Munge(rec []any) error {
if x.mungeFn == nil { if x.mungeFn == nil {
return nil return nil
} }
@ -86,7 +86,7 @@ func (x *StmtExecer) Munge(rec []interface{}) error {
// Exec executes the statement. The caller should invoke Munge on // Exec executes the statement. The caller should invoke Munge on
// each row of values prior to passing those values to Exec. // each row of values prior to passing those values to Exec.
func (x *StmtExecer) Exec(ctx context.Context, args ...interface{}) (affected int64, err error) { func (x *StmtExecer) Exec(ctx context.Context, args ...any) (affected int64, err error) {
return x.execFn(ctx, args...) return x.execFn(ctx, args...)
} }
@ -108,8 +108,8 @@ func (x *StmtExecer) Close() error {
// copied directly into rec, and its index is returned in skipped. // copied directly into rec, and its index is returned in skipped.
// The caller must take appropriate action to deal with all // The caller must take appropriate action to deal with all
// elements of rec listed in skipped. // elements of rec listed in skipped.
func NewRecordFromScanRow(meta sqlz.RecordMeta, row []interface{}, skip []int) (rec sqlz.Record, skipped []int) { func NewRecordFromScanRow(meta sqlz.RecordMeta, row []any, skip []int) (rec sqlz.Record, skipped []int) {
rec = make([]interface{}, len(row)) rec = make([]any, len(row))
// For convenience, make a map of the skip row indices. // For convenience, make a map of the skip row indices.
mSkip := map[int]struct{}{} mSkip := map[int]struct{}{}
@ -356,7 +356,7 @@ func PrepareInsertStmt(ctx context.Context, drvr SQLDriver, db sqlz.Preparer, de
type BatchInsert struct { type BatchInsert struct {
// RecordCh is the channel that the caller sends records on. The // RecordCh is the channel that the caller sends records on. The
// caller must close RecordCh when done. // caller must close RecordCh when done.
RecordCh chan<- []interface{} RecordCh chan<- []any
// ErrCh returns any errors that occur during insert. ErrCh is // ErrCh returns any errors that occur during insert. ErrCh is
// closed by BatchInsert when processing is complete. // closed by BatchInsert when processing is complete.
@ -376,7 +376,7 @@ func (bi *BatchInsert) Written() int64 {
// Munge should be invoked on every record before sending // Munge should be invoked on every record before sending
// on RecordCh. // on RecordCh.
func (bi BatchInsert) Munge(rec []interface{}) error { func (bi BatchInsert) Munge(rec []any) error {
return bi.mungeFn(rec) return bi.mungeFn(rec)
} }
@ -391,7 +391,7 @@ func NewBatchInsert(ctx context.Context, log lg.Log, drvr SQLDriver, db sqlz.DB,
return nil, err return nil, err
} }
recCh := make(chan []interface{}, batchSize*8) recCh := make(chan []any, batchSize*8)
errCh := make(chan error, 1) errCh := make(chan error, 1)
rowLen := len(destColNames) rowLen := len(destColNames)
@ -406,9 +406,9 @@ func NewBatchInsert(ctx context.Context, log lg.Log, drvr SQLDriver, db sqlz.DB,
// vals holds rows of values as a single slice. That is, vals is // vals holds rows of values as a single slice. That is, vals is
// a bunch of record fields appended to one big slice to pass // a bunch of record fields appended to one big slice to pass
// as args to the INSERT statement // as args to the INSERT statement
vals := make([]interface{}, 0, rowLen*batchSize) vals := make([]any, 0, rowLen*batchSize)
var rec []interface{} var rec []any
var affected int64 var affected int64
defer func() { defer func() {
@ -584,7 +584,7 @@ func DefaultInsertMungeFunc(destTbl string, destMeta sqlz.RecordMeta) InsertMung
// mungeSetZeroValue is invoked when rec[i] is nil, but // mungeSetZeroValue is invoked when rec[i] is nil, but
// destMeta[i] is not nullable. // destMeta[i] is not nullable.
func mungeSetZeroValue(i int, rec []interface{}, destMeta sqlz.RecordMeta) { func mungeSetZeroValue(i int, rec []any, destMeta sqlz.RecordMeta) {
// REVISIT: do we need to do special handling for kind.Datetime // REVISIT: do we need to do special handling for kind.Datetime
// and kind.Time (e.g. "00:00" for time)? // and kind.Time (e.g. "00:00" for time)?
z := reflect.Zero(destMeta[i].ScanType()).Interface() z := reflect.Zero(destMeta[i].ScanType()).Interface()

View File

@ -113,7 +113,7 @@ func newEngine(ctx context.Context, log lg.Log, dbOpener driver.DatabaseOpener,
// before recw has finished writing, thus the caller may wish // before recw has finished writing, thus the caller may wish
// to wait for recw to complete. // to wait for recw to complete.
// The caller is responsible for closing dbase. // The caller is responsible for closing dbase.
func QuerySQL(ctx context.Context, log lg.Log, dbase driver.Database, recw RecordWriter, query string, args ...interface{}) error { func QuerySQL(ctx context.Context, log lg.Log, dbase driver.Database, recw RecordWriter, query string, args ...any) error {
rows, err := dbase.DB().QueryContext(ctx, query, args...) rows, err := dbase.DB().QueryContext(ctx, query, args...)
if err != nil { if err != nil {
return errz.Wrapf(err, `SQL query against %s failed: %s`, dbase.Source().Handle, query) return errz.Wrapf(err, `SQL query against %s failed: %s`, dbase.Source().Handle, query)

View File

@ -47,7 +47,7 @@ func (s *Set) UnmarshalJSON(b []byte) error {
} }
// MarshalYAML implements yaml.Marshaler. // MarshalYAML implements yaml.Marshaler.
func (s *Set) MarshalYAML() (interface{}, error) { func (s *Set) MarshalYAML() (any, error) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
@ -55,7 +55,7 @@ func (s *Set) MarshalYAML() (interface{}, error) {
} }
// UnmarshalYAML implements yaml.Unmarshaler. // UnmarshalYAML implements yaml.Unmarshaler.
func (s *Set) UnmarshalYAML(unmarshal func(interface{}) error) error { func (s *Set) UnmarshalYAML(unmarshal func(any) error) error {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()

View File

@ -319,7 +319,7 @@ func (h *Helper) RowCount(src *source.Source, tbl string) int64 {
// CreateTable creates a new table in src, and inserts data, returning // CreateTable creates a new table in src, and inserts data, returning
// the number of data rows inserted. If dropAfter is true, the created // the number of data rows inserted. If dropAfter is true, the created
// table is dropped when t.Cleanup is run. // table is dropped when t.Cleanup is run.
func (h *Helper) CreateTable(dropAfter bool, src *source.Source, tblDef *sqlmodel.TableDef, data ...[]interface{}) (affected int64) { func (h *Helper) CreateTable(dropAfter bool, src *source.Source, tblDef *sqlmodel.TableDef, data ...[]any) (affected int64) {
dbase := h.openNew(src) dbase := h.openNew(src)
defer h.Log.WarnIfCloseError(dbase) defer h.Log.WarnIfCloseError(dbase)
@ -340,7 +340,7 @@ func (h *Helper) CreateTable(dropAfter bool, src *source.Source, tblDef *sqlmode
// Insert inserts records for cols into src.tbl, returning the number of // Insert inserts records for cols into src.tbl, returning the number of
// records inserted. Note that the records arg may be mutated by src's // records inserted. Note that the records arg may be mutated by src's
// driver InsertMungeFunc. // driver InsertMungeFunc.
func (h *Helper) Insert(src *source.Source, tbl string, cols []string, records ...[]interface{}) (affected int64) { func (h *Helper) Insert(src *source.Source, tbl string, cols []string, records ...[]any) (affected int64) {
if len(records) == 0 { if len(records) == 0 {
return 0 return 0
} }
@ -429,7 +429,7 @@ func (h *Helper) DropTable(src *source.Source, tbl string) {
// against src, returning a sink to which all records have // against src, returning a sink to which all records have
// been written. Note that QuerySQL uses the // been written. Note that QuerySQL uses the
// same Database instance as returned by h.Open. // same Database instance as returned by h.Open.
func (h *Helper) QuerySQL(src *source.Source, query string, args ...interface{}) (*RecordSink, error) { func (h *Helper) QuerySQL(src *source.Source, query string, args ...any) (*RecordSink, error) {
dbase := h.Open(src) dbase := h.Open(src)
sink := &RecordSink{} sink := &RecordSink{}
@ -449,7 +449,7 @@ func (h *Helper) QuerySQL(src *source.Source, query string, args ...interface{})
// ExecSQL is a convenience wrapper for sql.DB.Exec that returns the // ExecSQL is a convenience wrapper for sql.DB.Exec that returns the
// rows affected, failing on any error. Note that ExecSQL uses the // rows affected, failing on any error. Note that ExecSQL uses the
// same Database instance as returned by h.Open. // same Database instance as returned by h.Open.
func (h *Helper) ExecSQL(src *source.Source, query string, args ...interface{}) (affected int64) { func (h *Helper) ExecSQL(src *source.Source, query string, args ...any) (affected int64) {
dbase := h.Open(src) dbase := h.Open(src)
res, err := dbase.DB().ExecContext(h.Context, query, args...) res, err := dbase.DB().ExecContext(h.Context, query, args...)
@ -636,7 +636,7 @@ func SkipShort(t *testing.T, skip bool) {
// is nil, nil is returned. If i has type *(*string), // is nil, nil is returned. If i has type *(*string),
// Val(i) returns string. // Val(i) returns string.
// Useful for testing. // Useful for testing.
func Val(i interface{}) interface{} { func Val(i any) any {
if i == nil { if i == nil {
return nil return nil
} }
@ -673,7 +673,7 @@ func TypeDetectors() []source.TypeDetectFunc {
// AssertCompareFunc matches several of the the testify/require funcs. // AssertCompareFunc matches several of the the testify/require funcs.
// It can be used to choose assertion comparison funcs in test cases. // It can be used to choose assertion comparison funcs in test cases.
type AssertCompareFunc func(require.TestingT, interface{}, interface{}, ...interface{}) type AssertCompareFunc func(require.TestingT, any, any, ...any)
// Verify that a sample of the require funcs match AssertCompareFunc. // Verify that a sample of the require funcs match AssertCompareFunc.
var ( var (
@ -693,7 +693,7 @@ var (
// testh.Name("path/to/file") --> "path_to_file" // testh.Name("path/to/file") --> "path_to_file"
// //
// Any element of arg that prints to empty string is skipped. // Any element of arg that prints to empty string is skipped.
func Name(args ...interface{}) string { func Name(args ...any) string {
var parts []string var parts []string
var s string var s string
for _, a := range args { for _, a := range args {

View File

@ -21,25 +21,25 @@ import (
func TestVal(t *testing.T) { func TestVal(t *testing.T) {
want := "hello" want := "hello"
var got interface{} var got any
if testh.Val(nil) != nil { if testh.Val(nil) != nil {
t.FailNow() t.FailNow()
} }
var v0 interface{} var v0 any
if testh.Val(v0) != nil { if testh.Val(v0) != nil {
t.FailNow() t.FailNow()
} }
var v1 = want var v1 = want
var v1a interface{} = want var v1a any = want
var v2 = &v1 var v2 = &v1
var v3 interface{} = &v1 var v3 any = &v1
var v4 = &v2 var v4 = &v2
var v5 = &v4 var v5 = &v4
vals := []interface{}{v1, v1a, v2, v3, v4, v5} vals := []any{v1, v1a, v2, v3, v4, v5}
for _, val := range vals { for _, val := range vals {
got = testh.Val(val) got = testh.Val(val)
@ -167,12 +167,12 @@ func TestHelper_Files(t *testing.T) {
func TestTName(t *testing.T) { func TestTName(t *testing.T) {
testCases := []struct { testCases := []struct {
a []interface{} a []any
want string want string
}{ }{
{a: []interface{}{}, want: "empty"}, {a: []any{}, want: "empty"},
{a: []interface{}{"test", 1}, want: "test_1"}, {a: []any{"test", 1}, want: "test_1"},
{a: []interface{}{"/file/path/name"}, want: "_file_path_name"}, {a: []any{"/file/path/name"}, want: "_file_path_name"},
} }
for _, tc := range testCases { for _, tc := range testCases {