diff options
Diffstat (limited to 'src/encoding')
38 files changed, 303 insertions, 303 deletions
diff --git a/src/encoding/ascii85/ascii85_test.go b/src/encoding/ascii85/ascii85_test.go index c637103942..9e6b34e997 100644 --- a/src/encoding/ascii85/ascii85_test.go +++ b/src/encoding/ascii85/ascii85_test.go @@ -42,7 +42,7 @@ var pairs = []testpair{ }, } -func testEqual(t *testing.T, msg string, args ...interface{}) bool { +func testEqual(t *testing.T, msg string, args ...any) bool { t.Helper() if args[len(args)-2] != args[len(args)-1] { t.Errorf(msg, args...) diff --git a/src/encoding/asn1/asn1.go b/src/encoding/asn1/asn1.go index d0e1c6b176..cad1d7b08f 100644 --- a/src/encoding/asn1/asn1.go +++ b/src/encoding/asn1/asn1.go @@ -695,7 +695,7 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam err = SyntaxError{"data truncated"} return } - var result interface{} + var result any if !t.isCompound && t.class == ClassUniversal { innerBytes := bytes[offset : offset+t.length] switch t.tag { @@ -1086,7 +1086,7 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { // // Other ASN.1 types are not supported; if it encounters them, // Unmarshal returns a parse error. -func Unmarshal(b []byte, val interface{}) (rest []byte, err error) { +func Unmarshal(b []byte, val any) (rest []byte, err error) { return UnmarshalWithParams(b, val, "") } @@ -1109,7 +1109,7 @@ func (e *invalidUnmarshalError) Error() string { // UnmarshalWithParams allows field parameters to be specified for the // top-level element. The form of the params is the same as the field tags. -func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) { +func UnmarshalWithParams(b []byte, val any, params string) (rest []byte, err error) { v := reflect.ValueOf(val) if v.Kind() != reflect.Pointer || v.IsNil() { return nil, &invalidUnmarshalError{reflect.TypeOf(val)} diff --git a/src/encoding/asn1/asn1_test.go b/src/encoding/asn1/asn1_test.go index 8985538468..b1e05b96ae 100644 --- a/src/encoding/asn1/asn1_test.go +++ b/src/encoding/asn1/asn1_test.go @@ -479,7 +479,7 @@ type TestSet struct { var unmarshalTestData = []struct { in []byte - out interface{} + out any }{ {[]byte{0x02, 0x01, 0x42}, newInt(0x42)}, {[]byte{0x05, 0x00}, &RawValue{0, 5, false, []byte{}, []byte{0x05, 0x00}}}, @@ -521,7 +521,7 @@ func TestUnmarshal(t *testing.T) { func TestUnmarshalWithNilOrNonPointer(t *testing.T) { tests := []struct { b []byte - v interface{} + v any want string }{ {b: []byte{0x05, 0x00}, v: nil, want: "asn1: Unmarshal recipient value is nil"}, @@ -567,7 +567,7 @@ type RelativeDistinguishedNameSET []AttributeTypeAndValue type AttributeTypeAndValue struct { Type ObjectIdentifier - Value interface{} + Value any } type Validity struct { @@ -998,9 +998,9 @@ func TestUnmarshalInvalidUTF8(t *testing.T) { } func TestMarshalNilValue(t *testing.T) { - nilValueTestData := []interface{}{ + nilValueTestData := []any{ nil, - struct{ V interface{} }{}, + struct{ V any }{}, } for i, test := range nilValueTestData { if _, err := Marshal(test); err == nil { diff --git a/src/encoding/asn1/marshal.go b/src/encoding/asn1/marshal.go index 5b4d786d49..c243349175 100644 --- a/src/encoding/asn1/marshal.go +++ b/src/encoding/asn1/marshal.go @@ -730,13 +730,13 @@ func makeField(v reflect.Value, params fieldParameters) (e encoder, err error) { // utf8: causes strings to be marshaled as ASN.1, UTF8String values // utc: causes time.Time to be marshaled as ASN.1, UTCTime values // generalized: causes time.Time to be marshaled as ASN.1, GeneralizedTime values -func Marshal(val interface{}) ([]byte, error) { +func Marshal(val any) ([]byte, error) { return MarshalWithParams(val, "") } // MarshalWithParams allows field parameters to be specified for the // top-level element. The form of the params is the same as the field tags. -func MarshalWithParams(val interface{}, params string) ([]byte, error) { +func MarshalWithParams(val any, params string) ([]byte, error) { e, err := makeField(reflect.ValueOf(val), parseFieldParameters(params)) if err != nil { return nil, err diff --git a/src/encoding/asn1/marshal_test.go b/src/encoding/asn1/marshal_test.go index f0217ba8a5..d9c3cf48fa 100644 --- a/src/encoding/asn1/marshal_test.go +++ b/src/encoding/asn1/marshal_test.go @@ -97,7 +97,7 @@ type testSET []int var PST = time.FixedZone("PST", -8*60*60) type marshalTest struct { - in interface{} + in any out string // hex encoded } @@ -196,7 +196,7 @@ func TestMarshal(t *testing.T) { } type marshalWithParamsTest struct { - in interface{} + in any params string out string // hex encoded } @@ -222,7 +222,7 @@ func TestMarshalWithParams(t *testing.T) { } type marshalErrTest struct { - in interface{} + in any err string } @@ -276,7 +276,7 @@ func TestMarshalOID(t *testing.T) { func TestIssue11130(t *testing.T) { data := []byte("\x06\x010") // == \x06\x01\x30 == OID = 0 (the figure) - var v interface{} + var v any // v has Zero value here and Elem() would panic _, err := Unmarshal(data, &v) if err != nil { @@ -299,7 +299,7 @@ func TestIssue11130(t *testing.T) { return } - var v1 interface{} + var v1 any _, err = Unmarshal(data1, &v1) if err != nil { t.Errorf("%v", err) @@ -382,7 +382,7 @@ func BenchmarkUnmarshal(b *testing.B) { type testCase struct { in []byte - out interface{} + out any } var testData []testCase for _, test := range unmarshalTestData { diff --git a/src/encoding/base32/base32_test.go b/src/encoding/base32/base32_test.go index 8fb22b9078..dbd2b613b4 100644 --- a/src/encoding/base32/base32_test.go +++ b/src/encoding/base32/base32_test.go @@ -42,7 +42,7 @@ var bigtest = testpair{ "KR3WC4ZAMJZGS3DMNFTSYIDBNZSCA5DIMUQHG3DJORUHSIDUN53GK4Y=", } -func testEqual(t *testing.T, msg string, args ...interface{}) bool { +func testEqual(t *testing.T, msg string, args ...any) bool { t.Helper() if args[len(args)-2] != args[len(args)-1] { t.Errorf(msg, args...) diff --git a/src/encoding/base64/base64_test.go b/src/encoding/base64/base64_test.go index 51047402bd..57256a3846 100644 --- a/src/encoding/base64/base64_test.go +++ b/src/encoding/base64/base64_test.go @@ -98,7 +98,7 @@ var bigtest = testpair{ "VHdhcyBicmlsbGlnLCBhbmQgdGhlIHNsaXRoeSB0b3Zlcw==", } -func testEqual(t *testing.T, msg string, args ...interface{}) bool { +func testEqual(t *testing.T, msg string, args ...any) bool { t.Helper() if args[len(args)-2] != args[len(args)-1] { t.Errorf(msg, args...) diff --git a/src/encoding/binary/binary.go b/src/encoding/binary/binary.go index 52417a7933..ee933461ee 100644 --- a/src/encoding/binary/binary.go +++ b/src/encoding/binary/binary.go @@ -159,7 +159,7 @@ func (bigEndian) GoString() string { return "binary.BigEndian" } // The error is EOF only if no bytes were read. // If an EOF happens after reading some but not all the bytes, // Read returns ErrUnexpectedEOF. -func Read(r io.Reader, order ByteOrder, data interface{}) error { +func Read(r io.Reader, order ByteOrder, data any) error { // Fast path for basic types and slices. if n := intDataSize(data); n != 0 { bs := make([]byte, n) @@ -268,7 +268,7 @@ func Read(r io.Reader, order ByteOrder, data interface{}) error { // and read from successive fields of the data. // When writing structs, zero values are written for fields // with blank (_) field names. -func Write(w io.Writer, order ByteOrder, data interface{}) error { +func Write(w io.Writer, order ByteOrder, data any) error { // Fast path for basic types and slices. if n := intDataSize(data); n != 0 { bs := make([]byte, n) @@ -392,7 +392,7 @@ func Write(w io.Writer, order ByteOrder, data interface{}) error { // Size returns how many bytes Write would generate to encode the value v, which // must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. // If v is neither of these, Size returns -1. -func Size(v interface{}) int { +func Size(v any) int { return dataSize(reflect.Indirect(reflect.ValueOf(v))) } @@ -696,7 +696,7 @@ func (e *encoder) skip(v reflect.Value) { // intDataSize returns the size of the data required to represent the data when encoded. // It returns zero if the type cannot be implemented by the fast path in Read or Write. -func intDataSize(data interface{}) int { +func intDataSize(data any) int { switch data := data.(type) { case bool, int8, uint8, *bool, *int8, *uint8: return 1 diff --git a/src/encoding/binary/binary_test.go b/src/encoding/binary/binary_test.go index 83af89e8a7..9e1b5f12db 100644 --- a/src/encoding/binary/binary_test.go +++ b/src/encoding/binary/binary_test.go @@ -113,7 +113,7 @@ var src = []byte{1, 2, 3, 4, 5, 6, 7, 8} var res = []int32{0x01020304, 0x05060708} var putbuf = []byte{0, 0, 0, 0, 0, 0, 0, 0} -func checkResult(t *testing.T, dir string, order ByteOrder, err error, have, want interface{}) { +func checkResult(t *testing.T, dir string, order ByteOrder, err error, have, want any) { if err != nil { t.Errorf("%v %v: %v", dir, order, err) return @@ -123,13 +123,13 @@ func checkResult(t *testing.T, dir string, order ByteOrder, err error, have, wan } } -func testRead(t *testing.T, order ByteOrder, b []byte, s1 interface{}) { +func testRead(t *testing.T, order ByteOrder, b []byte, s1 any) { var s2 Struct err := Read(bytes.NewReader(b), order, &s2) checkResult(t, "Read", order, err, s2, s1) } -func testWrite(t *testing.T, order ByteOrder, b []byte, s1 interface{}) { +func testWrite(t *testing.T, order ByteOrder, b []byte, s1 any) { buf := new(bytes.Buffer) err := Write(buf, order, s1) checkResult(t, "Write", order, err, buf.Bytes(), b) @@ -175,7 +175,7 @@ func TestReadBoolSlice(t *testing.T) { } // Addresses of arrays are easier to manipulate with reflection than are slices. -var intArrays = []interface{}{ +var intArrays = []any{ &[100]int8{}, &[100]int16{}, &[100]int32{}, @@ -304,7 +304,7 @@ func TestSizeStructCache(t *testing.T) { count := func() int { var i int - structSize.Range(func(_, _ interface{}) bool { + structSize.Range(func(_, _ any) bool { i++ return true }) @@ -329,7 +329,7 @@ func TestSizeStructCache(t *testing.T) { } testcases := []struct { - val interface{} + val any want int }{ {new(foo), 1}, @@ -376,7 +376,7 @@ func TestUnexportedRead(t *testing.T) { func TestReadErrorMsg(t *testing.T) { var buf bytes.Buffer - read := func(data interface{}) { + read := func(data any) { err := Read(&buf, LittleEndian, data) want := "binary.Read: invalid type " + reflect.TypeOf(data).String() if err == nil { @@ -457,7 +457,7 @@ func TestReadInvalidDestination(t *testing.T) { } func testReadInvalidDestination(t *testing.T, order ByteOrder) { - destinations := []interface{}{ + destinations := []any{ int8(0), int16(0), int32(0), diff --git a/src/encoding/binary/example_test.go b/src/encoding/binary/example_test.go index b994b897ce..4c10daaf68 100644 --- a/src/encoding/binary/example_test.go +++ b/src/encoding/binary/example_test.go @@ -24,7 +24,7 @@ func ExampleWrite() { func ExampleWrite_multi() { buf := new(bytes.Buffer) - var data = []interface{}{ + var data = []any{ uint16(61374), int8(-54), uint8(254), diff --git a/src/encoding/gob/codec_test.go b/src/encoding/gob/codec_test.go index f38e88b638..1ca9d878ee 100644 --- a/src/encoding/gob/codec_test.go +++ b/src/encoding/gob/codec_test.go @@ -1178,13 +1178,13 @@ func TestInterface(t *testing.T) { // A struct with all basic types, stored in interfaces. type BasicInterfaceItem struct { - Int, Int8, Int16, Int32, Int64 interface{} - Uint, Uint8, Uint16, Uint32, Uint64 interface{} - Float32, Float64 interface{} - Complex64, Complex128 interface{} - Bool interface{} - String interface{} - Bytes interface{} + Int, Int8, Int16, Int32, Int64 any + Uint, Uint8, Uint16, Uint32, Uint64 any + Float32, Float64 any + Complex64, Complex128 any + Bool any + String any + Bytes any } func TestInterfaceBasic(t *testing.T) { @@ -1223,8 +1223,8 @@ func TestInterfaceBasic(t *testing.T) { type String string type PtrInterfaceItem struct { - Str1 interface{} // basic - Str2 interface{} // derived + Str1 any // basic + Str2 any // derived } // We'll send pointers; should receive values. @@ -1318,7 +1318,7 @@ func TestUnexportedFields(t *testing.T) { } } -var singletons = []interface{}{ +var singletons = []any{ true, 7, uint(10), @@ -1354,9 +1354,9 @@ type DT struct { A int B string C float64 - I interface{} - J interface{} - I_nil interface{} + I any + J any + I_nil any M map[string]int T [3]int S []string @@ -1396,7 +1396,7 @@ func TestDebugStruct(t *testing.T) { debugFunc(debugBuffer) } -func encFuzzDec(rng *rand.Rand, in interface{}) error { +func encFuzzDec(rng *rand.Rand, in any) error { buf := new(bytes.Buffer) enc := NewEncoder(buf) if err := enc.Encode(&in); err != nil { @@ -1411,7 +1411,7 @@ func encFuzzDec(rng *rand.Rand, in interface{}) error { } dec := NewDecoder(buf) - var e interface{} + var e any if err := dec.Decode(&e); err != nil { return err } @@ -1425,7 +1425,7 @@ func TestFuzz(t *testing.T) { } // all possible inputs - input := []interface{}{ + input := []any{ new(int), new(float32), new(float64), @@ -1450,7 +1450,7 @@ func TestFuzzRegressions(t *testing.T) { testFuzz(t, 1330522872628565000, 100, new(int)) } -func testFuzz(t *testing.T, seed int64, n int, input ...interface{}) { +func testFuzz(t *testing.T, seed int64, n int, input ...any) { for _, e := range input { t.Logf("seed=%d n=%d e=%T", seed, n, e) rng := rand.New(rand.NewSource(seed)) diff --git a/src/encoding/gob/debug.go b/src/encoding/gob/debug.go index 5ceb2bfac7..b6d5a3e95c 100644 --- a/src/encoding/gob/debug.go +++ b/src/encoding/gob/debug.go @@ -118,7 +118,7 @@ type debugger struct { // dump prints the next nBytes of the input. // It arranges to print the output aligned from call to // call, to make it easy to see what has been consumed. -func (deb *debugger) dump(format string, args ...interface{}) { +func (deb *debugger) dump(format string, args ...any) { if !dumpBytes { return } diff --git a/src/encoding/gob/decoder.go b/src/encoding/gob/decoder.go index 96e215eb8c..86f54b4193 100644 --- a/src/encoding/gob/decoder.go +++ b/src/encoding/gob/decoder.go @@ -186,7 +186,7 @@ func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId { // correct type for the next data item received. // If the input is at EOF, Decode returns io.EOF and // does not modify e. -func (dec *Decoder) Decode(e interface{}) error { +func (dec *Decoder) Decode(e any) error { if e == nil { return dec.DecodeValue(reflect.Value{}) } diff --git a/src/encoding/gob/encode.go b/src/encoding/gob/encode.go index e49b452f6c..548d614f52 100644 --- a/src/encoding/gob/encode.go +++ b/src/encoding/gob/encode.go @@ -40,7 +40,7 @@ type encBuffer struct { } var encBufferPool = sync.Pool{ - New: func() interface{} { + New: func() any { e := new(encBuffer) e.data = e.scratch[0:0] return e diff --git a/src/encoding/gob/encoder.go b/src/encoding/gob/encoder.go index 32865a7ede..5a80e6c3e8 100644 --- a/src/encoding/gob/encoder.go +++ b/src/encoding/gob/encoder.go @@ -172,7 +172,7 @@ func (enc *Encoder) sendType(w io.Writer, state *encoderState, origt reflect.Typ // Encode transmits the data item represented by the empty interface value, // guaranteeing that all necessary type information has been transmitted first. // Passing a nil pointer to Encoder will panic, as they cannot be transmitted by gob. -func (enc *Encoder) Encode(e interface{}) error { +func (enc *Encoder) Encode(e any) error { return enc.EncodeValue(reflect.ValueOf(e)) } diff --git a/src/encoding/gob/encoder_test.go b/src/encoding/gob/encoder_test.go index a358d5bc30..6934841b3a 100644 --- a/src/encoding/gob/encoder_test.go +++ b/src/encoding/gob/encoder_test.go @@ -18,7 +18,7 @@ import ( // Test basic operations in a safe manner. func TestBasicEncoderDecoder(t *testing.T) { - var values = []interface{}{ + var values = []any{ true, int(123), int8(123), @@ -228,7 +228,7 @@ func TestEncoderDecoder(t *testing.T) { // Run one value through the encoder/decoder, but use the wrong type. // Input is always an ET1; we compare it to whatever is under 'e'. -func badTypeCheck(e interface{}, shouldFail bool, msg string, t *testing.T) { +func badTypeCheck(e any, shouldFail bool, msg string, t *testing.T) { b := new(bytes.Buffer) enc := NewEncoder(b) et1 := new(ET1) @@ -256,7 +256,7 @@ func TestWrongTypeDecoder(t *testing.T) { } // Types not supported at top level by the Encoder. -var unsupportedValues = []interface{}{ +var unsupportedValues = []any{ make(chan int), func(a int) bool { return true }, } @@ -272,7 +272,7 @@ func TestUnsupported(t *testing.T) { } } -func encAndDec(in, out interface{}) error { +func encAndDec(in, out any) error { b := new(bytes.Buffer) enc := NewEncoder(b) err := enc.Encode(in) @@ -418,8 +418,8 @@ var testMap map[string]int var testArray [7]int type SingleTest struct { - in interface{} - out interface{} + in any + out any err string } @@ -536,7 +536,7 @@ func TestInterfaceIndirect(t *testing.T) { // encoder and decoder don't skew with respect to type definitions. type Struct0 struct { - I interface{} + I any } type NewType0 struct { @@ -544,7 +544,7 @@ type NewType0 struct { } type ignoreTest struct { - in, out interface{} + in, out any } var ignoreTests = []ignoreTest{ @@ -559,7 +559,7 @@ var ignoreTests = []ignoreTest{ // Decode struct containing an interface into a nil. {&Struct0{&NewType0{"value0"}}, nil}, // Decode singleton slice of interfaces into a nil. - {[]interface{}{"hi", &NewType0{"value1"}, 23}, nil}, + {[]any{"hi", &NewType0{"value1"}, 23}, nil}, } func TestDecodeIntoNothing(t *testing.T) { @@ -621,7 +621,7 @@ func TestIgnoreRecursiveType(t *testing.T) { // Another bug from golang-nuts, involving nested interfaces. type Bug0Outer struct { - Bug0Field interface{} + Bug0Field any } type Bug0Inner struct { @@ -635,7 +635,7 @@ func TestNestedInterfaces(t *testing.T) { Register(new(Bug0Outer)) Register(new(Bug0Inner)) f := &Bug0Outer{&Bug0Outer{&Bug0Inner{7}}} - var v interface{} = f + var v any = f err := e.Encode(&v) if err != nil { t.Fatal("Encode:", err) @@ -694,7 +694,7 @@ func TestMapBug1(t *testing.T) { } func TestGobMapInterfaceEncode(t *testing.T) { - m := map[string]interface{}{ + m := map[string]any{ "up": uintptr(0), "i0": []int{-1}, "i1": []int8{-1}, @@ -876,10 +876,10 @@ func TestGobPtrSlices(t *testing.T) { // getDecEnginePtr cached engine for ut.base instead of ut.user so we passed // a *map and then tried to reuse its engine to decode the inner map. func TestPtrToMapOfMap(t *testing.T) { - Register(make(map[string]interface{})) - subdata := make(map[string]interface{}) + Register(make(map[string]any)) + subdata := make(map[string]any) subdata["bar"] = "baz" - data := make(map[string]interface{}) + data := make(map[string]any) data["foo"] = subdata b := new(bytes.Buffer) @@ -887,7 +887,7 @@ func TestPtrToMapOfMap(t *testing.T) { if err != nil { t.Fatal("encode:", err) } - var newData map[string]interface{} + var newData map[string]any err = NewDecoder(b).Decode(&newData) if err != nil { t.Fatal("decode:", err) @@ -927,7 +927,7 @@ func TestTopLevelNilPointer(t *testing.T) { } } -func encodeAndRecover(value interface{}) (encodeErr, panicErr error) { +func encodeAndRecover(value any) (encodeErr, panicErr error) { defer func() { e := recover() if e != nil { @@ -959,7 +959,7 @@ func TestNilPointerPanics(t *testing.T) { ) testCases := []struct { - value interface{} + value any mustPanic bool }{ {nilStringPtr, true}, @@ -991,7 +991,7 @@ func TestNilPointerPanics(t *testing.T) { func TestNilPointerInsideInterface(t *testing.T) { var ip *int si := struct { - I interface{} + I any }{ I: ip, } @@ -1049,7 +1049,7 @@ type Z struct { func Test29ElementSlice(t *testing.T) { Register(Z{}) - src := make([]interface{}, 100) // Size needs to be bigger than size of type definition. + src := make([]any, 100) // Size needs to be bigger than size of type definition. for i := range src { src[i] = Z{} } @@ -1060,7 +1060,7 @@ func Test29ElementSlice(t *testing.T) { return } - var dst []interface{} + var dst []any err = NewDecoder(buf).Decode(&dst) if err != nil { t.Errorf("decode: %v", err) @@ -1091,9 +1091,9 @@ func TestErrorForHugeSlice(t *testing.T) { } type badDataTest struct { - input string // The input encoded as a hex string. - error string // A substring of the error that should result. - data interface{} // What to decode into. + input string // The input encoded as a hex string. + error string // A substring of the error that should result. + data any // What to decode into. } var badDataTests = []badDataTest{ diff --git a/src/encoding/gob/error.go b/src/encoding/gob/error.go index 949333bc03..3c9515b5ed 100644 --- a/src/encoding/gob/error.go +++ b/src/encoding/gob/error.go @@ -20,7 +20,7 @@ type gobError struct { // errorf is like error_ but takes Printf-style arguments to construct an error. // It always prefixes the message with "gob: ". -func errorf(format string, args ...interface{}) { +func errorf(format string, args ...any) { error_(fmt.Errorf("gob: "+format, args...)) } diff --git a/src/encoding/gob/gobencdec_test.go b/src/encoding/gob/gobencdec_test.go index 6d2c8db42d..1d5dde22a4 100644 --- a/src/encoding/gob/gobencdec_test.go +++ b/src/encoding/gob/gobencdec_test.go @@ -734,7 +734,7 @@ func (a *isZeroBugArray) GobDecode(data []byte) error { } type isZeroBugInterface struct { - I interface{} + I any } func (i isZeroBugInterface) GobEncode() (b []byte, e error) { diff --git a/src/encoding/gob/timing_test.go b/src/encoding/gob/timing_test.go index 516aeea92c..bdee39c447 100644 --- a/src/encoding/gob/timing_test.go +++ b/src/encoding/gob/timing_test.go @@ -20,7 +20,7 @@ type Bench struct { D []byte } -func benchmarkEndToEnd(b *testing.B, ctor func() interface{}, pipe func() (r io.Reader, w io.Writer, err error)) { +func benchmarkEndToEnd(b *testing.B, ctor func() any, pipe func() (r io.Reader, w io.Writer, err error)) { b.RunParallel(func(pb *testing.PB) { r, w, err := pipe() if err != nil { @@ -41,7 +41,7 @@ func benchmarkEndToEnd(b *testing.B, ctor func() interface{}, pipe func() (r io. } func BenchmarkEndToEndPipe(b *testing.B) { - benchmarkEndToEnd(b, func() interface{} { + benchmarkEndToEnd(b, func() any { return &Bench{7, 3.2, "now is the time", bytes.Repeat([]byte("for all good men"), 100)} }, func() (r io.Reader, w io.Writer, err error) { r, w, err = os.Pipe() @@ -50,7 +50,7 @@ func BenchmarkEndToEndPipe(b *testing.B) { } func BenchmarkEndToEndByteBuffer(b *testing.B) { - benchmarkEndToEnd(b, func() interface{} { + benchmarkEndToEnd(b, func() any { return &Bench{7, 3.2, "now is the time", bytes.Repeat([]byte("for all good men"), 100)} }, func() (r io.Reader, w io.Writer, err error) { var buf bytes.Buffer @@ -59,10 +59,10 @@ func BenchmarkEndToEndByteBuffer(b *testing.B) { } func BenchmarkEndToEndSliceByteBuffer(b *testing.B) { - benchmarkEndToEnd(b, func() interface{} { + benchmarkEndToEnd(b, func() any { v := &Bench{7, 3.2, "now is the time", nil} Register(v) - arr := make([]interface{}, 100) + arr := make([]any, 100) for i := range arr { arr[i] = v } @@ -133,7 +133,7 @@ func TestCountDecodeMallocs(t *testing.T) { } } -func benchmarkEncodeSlice(b *testing.B, a interface{}) { +func benchmarkEncodeSlice(b *testing.B, a any) { b.ResetTimer() b.RunParallel(func(pb *testing.PB) { var buf bytes.Buffer @@ -182,7 +182,7 @@ func BenchmarkEncodeStringSlice(b *testing.B) { } func BenchmarkEncodeInterfaceSlice(b *testing.B) { - a := make([]interface{}, 1000) + a := make([]any, 1000) for i := range a { a[i] = "now is the time" } @@ -217,7 +217,7 @@ func (b *benchmarkBuf) reset() { b.offset = 0 } -func benchmarkDecodeSlice(b *testing.B, a interface{}) { +func benchmarkDecodeSlice(b *testing.B, a any) { var buf bytes.Buffer enc := NewEncoder(&buf) err := enc.Encode(a) @@ -295,7 +295,7 @@ func BenchmarkDecodeBytesSlice(b *testing.B) { } func BenchmarkDecodeInterfaceSlice(b *testing.B) { - a := make([]interface{}, 1000) + a := make([]any, 1000) for i := range a { a[i] = "now is the time" } diff --git a/src/encoding/gob/type.go b/src/encoding/gob/type.go index 412a348137..6e2c724232 100644 --- a/src/encoding/gob/type.go +++ b/src/encoding/gob/type.go @@ -244,7 +244,7 @@ var ( tBytes = bootstrapType("bytes", (*[]byte)(nil), 5) tString = bootstrapType("string", (*string)(nil), 6) tComplex = bootstrapType("complex", (*complex128)(nil), 7) - tInterface = bootstrapType("interface", (*interface{})(nil), 8) + tInterface = bootstrapType("interface", (*any)(nil), 8) // Reserve some Ids for compatible expansion tReserved7 = bootstrapType("_reserved1", (*struct{ r7 int })(nil), 9) tReserved6 = bootstrapType("_reserved1", (*struct{ r6 int })(nil), 10) @@ -611,7 +611,7 @@ func checkId(want, got typeId) { // used for building the basic types; called only from init(). the incoming // interface always refers to a pointer. -func bootstrapType(name string, e interface{}, expect typeId) typeId { +func bootstrapType(name string, e any, expect typeId) typeId { rt := reflect.TypeOf(e).Elem() _, present := types[rt] if present { @@ -804,7 +804,7 @@ var ( // RegisterName is like Register but uses the provided name rather than the // type's default. -func RegisterName(name string, value interface{}) { +func RegisterName(name string, value any) { if name == "" { // reserved for nil panic("attempt to register empty name") @@ -833,7 +833,7 @@ func RegisterName(name string, value interface{}) { // transferred as implementations of interface values need to be registered. // Expecting to be used only during initialization, it panics if the mapping // between types and names is not a bijection. -func Register(value interface{}) { +func Register(value any) { // Default to printed representation for unnamed types rt := reflect.TypeOf(value) name := rt.String() diff --git a/src/encoding/gob/type_test.go b/src/encoding/gob/type_test.go index fa3e802d4e..f5f8db8bcb 100644 --- a/src/encoding/gob/type_test.go +++ b/src/encoding/gob/type_test.go @@ -168,7 +168,7 @@ type N2 struct{} // See comment in type.go/Register. func TestRegistrationNaming(t *testing.T) { testCases := []struct { - t interface{} + t any name string }{ {&N1{}, "*gob.N1"}, @@ -231,7 +231,7 @@ func TestTypeRace(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf) dec := NewDecoder(&buf) - var x interface{} + var x any switch i { case 0: x = &N1{} diff --git a/src/encoding/json/bench_test.go b/src/encoding/json/bench_test.go index 73c7b09fb6..95609140b0 100644 --- a/src/encoding/json/bench_test.go +++ b/src/encoding/json/bench_test.go @@ -192,7 +192,7 @@ func BenchmarkDecoderStream(b *testing.B) { var buf bytes.Buffer dec := NewDecoder(&buf) buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n") - var x interface{} + var x any if err := dec.Decode(&x); err != nil { b.Fatal("Decode:", err) } diff --git a/src/encoding/json/decode.go b/src/encoding/json/decode.go index df4c5e1a16..555df0b7e8 100644 --- a/src/encoding/json/decode.go +++ b/src/encoding/json/decode.go @@ -93,7 +93,7 @@ import ( // Instead, they are replaced by the Unicode replacement // character U+FFFD. // -func Unmarshal(data []byte, v interface{}) error { +func Unmarshal(data []byte, v any) error { // Check for well-formedness. // Avoids filling out half a data structure // before discovering a JSON syntax error. @@ -167,7 +167,7 @@ func (e *InvalidUnmarshalError) Error() string { return "json: Unmarshal(nil " + e.Type.String() + ")" } -func (d *decodeState) unmarshal(v interface{}) error { +func (d *decodeState) unmarshal(v any) error { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Pointer || rv.IsNil() { return &InvalidUnmarshalError{reflect.TypeOf(v)} @@ -398,7 +398,7 @@ type unquotedValue struct{} // quoted string literal or literal null into an interface value. // If it finds anything other than a quoted string literal or null, // valueQuoted returns unquotedValue{}. -func (d *decodeState) valueQuoted() interface{} { +func (d *decodeState) valueQuoted() any { switch d.opcode { default: panic(phasePanicMsg) @@ -840,7 +840,7 @@ func (d *decodeState) object(v reflect.Value) error { // convertNumber converts the number literal s to a float64 or a Number // depending on the setting of d.useNumber. -func (d *decodeState) convertNumber(s string) (interface{}, error) { +func (d *decodeState) convertNumber(s string) (any, error) { if d.useNumber { return Number(s), nil } @@ -1037,7 +1037,7 @@ func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool // but they avoid the weight of reflection in this common case. // valueInterface is like value but returns interface{} -func (d *decodeState) valueInterface() (val interface{}) { +func (d *decodeState) valueInterface() (val any) { switch d.opcode { default: panic(phasePanicMsg) @@ -1054,8 +1054,8 @@ func (d *decodeState) valueInterface() (val interface{}) { } // arrayInterface is like array but returns []interface{}. -func (d *decodeState) arrayInterface() []interface{} { - var v = make([]interface{}, 0) +func (d *decodeState) arrayInterface() []any { + var v = make([]any, 0) for { // Look ahead for ] - can only happen on first iteration. d.scanWhile(scanSkipSpace) @@ -1080,8 +1080,8 @@ func (d *decodeState) arrayInterface() []interface{} { } // objectInterface is like object but returns map[string]interface{}. -func (d *decodeState) objectInterface() map[string]interface{} { - m := make(map[string]interface{}) +func (d *decodeState) objectInterface() map[string]any { + m := make(map[string]any) for { // Read opening " of string key or closing }. d.scanWhile(scanSkipSpace) @@ -1131,7 +1131,7 @@ func (d *decodeState) objectInterface() map[string]interface{} { // literalInterface consumes and returns a literal from d.data[d.off-1:] and // it reads the following byte ahead. The first byte of the literal has been // read already (that's how the caller knows it's a literal). -func (d *decodeState) literalInterface() interface{} { +func (d *decodeState) literalInterface() any { // All bytes inside literal return scanContinue op code. start := d.readIndex() d.rescanLiteral() diff --git a/src/encoding/json/decode_test.go b/src/encoding/json/decode_test.go index 96bf9fb5ff..c2c036b609 100644 --- a/src/encoding/json/decode_test.go +++ b/src/encoding/json/decode_test.go @@ -31,7 +31,7 @@ type U struct { } type V struct { - F1 interface{} + F1 any F2 int32 F3 Number F4 *VOuter @@ -62,18 +62,18 @@ func (*SS) UnmarshalJSON(data []byte) error { // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and // without UseNumber -var ifaceNumAsFloat64 = map[string]interface{}{ +var ifaceNumAsFloat64 = map[string]any{ "k1": float64(1), "k2": "s", - "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)}, - "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)}, + "k3": []any{float64(1), float64(2.0), float64(3e-3)}, + "k4": map[string]any{"kk1": "s", "kk2": float64(2)}, } -var ifaceNumAsNumber = map[string]interface{}{ +var ifaceNumAsNumber = map[string]any{ "k1": Number("1"), "k2": "s", - "k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")}, - "k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")}, + "k3": []any{Number("1"), Number("2.0"), Number("3e-3")}, + "k4": map[string]any{"kk1": "s", "kk2": Number("2")}, } type tx struct { @@ -262,9 +262,9 @@ type Ambig struct { } type XYZ struct { - X interface{} - Y interface{} - Z interface{} + X any + Y any + Z any } type unexportedWithMethods struct{} @@ -389,8 +389,8 @@ type mapStringToStringData struct { type unmarshalTest struct { in string - ptr interface{} // new(type) - out interface{} + ptr any // new(type) + out any err error useNumber bool golden bool @@ -414,13 +414,13 @@ var unmarshalTests = []unmarshalTest{ {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")}, - {in: `2`, ptr: new(interface{}), out: float64(2.0)}, - {in: `2`, ptr: new(interface{}), out: Number("2"), useNumber: true}, + {in: `2`, ptr: new(any), out: float64(2.0)}, + {in: `2`, ptr: new(any), out: Number("2"), useNumber: true}, {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"}, {in: `"http:\/\/"`, ptr: new(string), out: "http://"}, {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"}, {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": 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{}}, @@ -428,8 +428,8 @@ var unmarshalTests = []unmarshalTest{ {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: 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(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: ifaceNumAsFloat64}, + {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 {in: "\n true ", ptr: new(bool), out: true}, @@ -472,10 +472,10 @@ var unmarshalTests = []unmarshalTest{ {in: `[1, 2, 3]`, ptr: new(MustNotUnmarshalJSON), err: errors.New("MustNotUnmarshalJSON was used")}, // empty array to interface test - {in: `[]`, ptr: new([]interface{}), out: []interface{}{}}, - {in: `null`, ptr: new([]interface{}), out: []interface{}(nil)}, - {in: `{"T":[]}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": []interface{}{}}}, - {in: `{"T":null}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": interface{}(nil)}}, + {in: `[]`, ptr: new([]any), out: []any{}}, + {in: `null`, ptr: new([]any), out: []any(nil)}, + {in: `{"T":[]}`, ptr: new(map[string]any), out: map[string]any{"T": []any{}}}, + {in: `{"T":null}`, ptr: new(map[string]any), out: map[string]any{"T": any(nil)}}, // composite tests {in: allValueIndent, ptr: new(All), out: allValue}, @@ -1176,7 +1176,7 @@ func TestUnmarshal(t *testing.T) { func TestUnmarshalMarshal(t *testing.T) { initBig() - var v interface{} + var v any if err := Unmarshal(jsonBig, &v); err != nil { t.Fatalf("Unmarshal: %v", err) } @@ -1248,7 +1248,7 @@ type Xint struct { func TestUnmarshalInterface(t *testing.T) { var xint Xint - var i interface{} = &xint + var i any = &xint if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil { t.Fatalf("Unmarshal: %v", err) } @@ -1382,8 +1382,8 @@ type All struct { PSmall *Small PPSmall **Small - Interface interface{} - PInterface *interface{} + Interface any + PInterface *any unexported int } @@ -1717,9 +1717,9 @@ func intpp(x *int) **int { } var interfaceSetTests = []struct { - pre interface{} + pre any json string - post interface{} + post any }{ {"foo", `"bar"`, "bar"}, {"foo", `2`, 2.0}, @@ -1738,7 +1738,7 @@ var interfaceSetTests = []struct { func TestInterfaceSet(t *testing.T) { for _, tt := range interfaceSetTests { - b := struct{ X interface{} }{tt.pre} + b := struct{ X any }{tt.pre} blob := `{"X":` + tt.json + `}` if err := Unmarshal([]byte(blob), &b); err != nil { t.Errorf("Unmarshal %#q: %v", blob, err) @@ -1768,7 +1768,7 @@ type NullTest struct { PBool *bool Map map[string]string Slice []string - Interface interface{} + Interface any PRaw *RawMessage PTime *time.Time @@ -1989,7 +1989,7 @@ func TestSliceOfCustomByte(t *testing.T) { } var decodeTypeErrorTests = []struct { - dest interface{} + dest any src string }{ {new(string), `{"user": "name"}`}, // issue 4628. @@ -2022,7 +2022,7 @@ var unmarshalSyntaxTests = []string{ } func TestUnmarshalSyntax(t *testing.T) { - var x interface{} + var x any for _, src := range unmarshalSyntaxTests { err := Unmarshal([]byte(src), &x) if _, ok := err.(*SyntaxError); !ok { @@ -2035,8 +2035,8 @@ func TestUnmarshalSyntax(t *testing.T) { // Issue 4660 type unexportedFields struct { Name string - m map[string]interface{} `json:"-"` - m2 map[string]interface{} `json:"abcd"` + m map[string]any `json:"-"` + m2 map[string]any `json:"abcd"` s []int `json:"-"` } @@ -2087,7 +2087,7 @@ func TestUnmarshalJSONLiteralError(t *testing.T) { // Issue 3717 func TestSkipArrayObjects(t *testing.T) { json := `[{}]` - var dest [0]interface{} + var dest [0]any err := Unmarshal([]byte(json), &dest) if err != nil { @@ -2102,8 +2102,8 @@ func TestPrefilled(t *testing.T) { // Values here change, cannot reuse table across runs. var prefillTests = []struct { in string - ptr interface{} - out interface{} + ptr any + out any }{ { in: `{"X": 1, "Y": 2}`, @@ -2112,8 +2112,8 @@ func TestPrefilled(t *testing.T) { }, { in: `{"X": 1, "Y": 2}`, - ptr: &map[string]interface{}{"X": float32(3), "Y": int16(4), "Z": 1.5}, - out: &map[string]interface{}{"X": float64(1), "Y": float64(2), "Z": 1.5}, + ptr: &map[string]any{"X": float32(3), "Y": int16(4), "Z": 1.5}, + out: &map[string]any{"X": float64(1), "Y": float64(2), "Z": 1.5}, }, { in: `[2]`, @@ -2150,7 +2150,7 @@ func TestPrefilled(t *testing.T) { } var invalidUnmarshalTests = []struct { - v interface{} + v any want string }{ {nil, "json: Unmarshal(nil)"}, @@ -2173,7 +2173,7 @@ func TestInvalidUnmarshal(t *testing.T) { } var invalidUnmarshalTextTests = []struct { - v interface{} + v any want string }{ {nil, "json: Unmarshal(nil)"}, @@ -2205,7 +2205,7 @@ func TestInvalidStringOption(t *testing.T) { M map[string]string `json:",string"` S []string `json:",string"` A [1]string `json:",string"` - I interface{} `json:",string"` + I any `json:",string"` P *int `json:",string"` }{M: make(map[string]string), S: make([]string, 0), I: num, P: &num} @@ -2276,8 +2276,8 @@ func TestUnmarshalEmbeddedUnexported(t *testing.T) { tests := []struct { in string - ptr interface{} - out interface{} + ptr any + out any err error }{{ // Error since we cannot set S1.embed1, but still able to set S1.R. @@ -2375,7 +2375,7 @@ func TestUnmarshalErrorAfterMultipleJSON(t *testing.T) { dec := NewDecoder(strings.NewReader(tt.in)) var err error for { - var v interface{} + var v any if err = dec.Decode(&v); err != nil { break } @@ -2403,7 +2403,7 @@ func TestUnmarshalPanic(t *testing.T) { // The decoder used to hang if decoding into an interface pointing to its own address. // See golang.org/issues/31740. func TestUnmarshalRecursivePointer(t *testing.T) { - var v interface{} + var v any v = &v data := []byte(`{"a": "b"}`) @@ -2517,36 +2517,36 @@ func TestUnmarshalMaxDepth(t *testing.T) { targets := []struct { name string - newValue func() interface{} + newValue func() any }{ { name: "unstructured", - newValue: func() interface{} { - var v interface{} + newValue: func() any { + var v any return &v }, }, { name: "typed named field", - newValue: func() interface{} { + newValue: func() any { v := struct { - A interface{} `json:"a"` + A any `json:"a"` }{} return &v }, }, { name: "typed missing field", - newValue: func() interface{} { + newValue: func() any { v := struct { - B interface{} `json:"b"` + B any `json:"b"` }{} return &v }, }, { name: "custom unmarshaler", - newValue: func() interface{} { + newValue: func() any { v := unmarshaler{} return &v }, diff --git a/src/encoding/json/encode.go b/src/encoding/json/encode.go index 4f40197797..1f5e3e446a 100644 --- a/src/encoding/json/encode.go +++ b/src/encoding/json/encode.go @@ -155,7 +155,7 @@ import ( // handle them. Passing cyclic structures to Marshal will result in // an error. // -func Marshal(v interface{}) ([]byte, error) { +func Marshal(v any) ([]byte, error) { e := newEncodeState() err := e.marshal(v, encOpts{escapeHTML: true}) @@ -172,7 +172,7 @@ func Marshal(v interface{}) ([]byte, error) { // MarshalIndent is like Marshal but applies Indent to format the output. // Each JSON element in the output will begin on a new line beginning with prefix // followed by one or more copies of indent according to the indentation nesting. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { +func MarshalIndent(v any, prefix, indent string) ([]byte, error) { b, err := Marshal(v) if err != nil { return nil, err @@ -294,7 +294,7 @@ type encodeState struct { // startDetectingCyclesAfter, so that we skip the work if we're within a // reasonable amount of nested pointers deep. ptrLevel uint - ptrSeen map[interface{}]struct{} + ptrSeen map[any]struct{} } const startDetectingCyclesAfter = 1000 @@ -311,7 +311,7 @@ func newEncodeState() *encodeState { e.ptrLevel = 0 return e } - return &encodeState{ptrSeen: make(map[interface{}]struct{})} + return &encodeState{ptrSeen: make(map[any]struct{})} } // jsonError is an error wrapper type for internal use only. @@ -319,7 +319,7 @@ func newEncodeState() *encodeState { // can distinguish intentional panics from this package. type jsonError struct{ error } -func (e *encodeState) marshal(v interface{}, opts encOpts) (err error) { +func (e *encodeState) marshal(v any, opts encOpts) (err error) { defer func() { if r := recover(); r != nil { if je, ok := r.(jsonError); ok { diff --git a/src/encoding/json/encode_test.go b/src/encoding/json/encode_test.go index 0dad951095..0b021f0074 100644 --- a/src/encoding/json/encode_test.go +++ b/src/encoding/json/encode_test.go @@ -28,8 +28,8 @@ type Optionals struct { Slr []string `json:"slr,random"` Slo []string `json:"slo,omitempty"` - Mr map[string]interface{} `json:"mr"` - Mo map[string]interface{} `json:",omitempty"` + Mr map[string]any `json:"mr"` + Mo map[string]any `json:",omitempty"` Fr float64 `json:"fr"` Fo float64 `json:"fo,omitempty"` @@ -59,8 +59,8 @@ var optionalsExpected = `{ func TestOmitEmpty(t *testing.T) { var o Optionals o.Sw = "something" - o.Mr = map[string]interface{}{} - o.Mo = map[string]interface{}{} + o.Mr = map[string]any{} + o.Mo = map[string]any{} got, err := MarshalIndent(&o, "", " ") if err != nil { @@ -180,16 +180,16 @@ type PointerCycle struct { var pointerCycle = &PointerCycle{} type PointerCycleIndirect struct { - Ptrs []interface{} + Ptrs []any } type RecursiveSlice []RecursiveSlice var ( pointerCycleIndirect = &PointerCycleIndirect{} - mapCycle = make(map[string]interface{}) - sliceCycle = []interface{}{nil} - sliceNoCycle = []interface{}{nil, nil} + mapCycle = make(map[string]any) + sliceCycle = []any{nil} + sliceNoCycle = []any{nil, nil} recursiveSliceCycle = []RecursiveSlice{nil} ) @@ -199,13 +199,13 @@ func init() { samePointerNoCycle.Ptr2 = ptr pointerCycle.Ptr = pointerCycle - pointerCycleIndirect.Ptrs = []interface{}{pointerCycleIndirect} + pointerCycleIndirect.Ptrs = []any{pointerCycleIndirect} mapCycle["x"] = mapCycle sliceCycle[0] = sliceCycle sliceNoCycle[1] = sliceNoCycle[:1] for i := startDetectingCyclesAfter; i > 0; i-- { - sliceNoCycle = []interface{}{sliceNoCycle} + sliceNoCycle = []any{sliceNoCycle} } recursiveSliceCycle[0] = recursiveSliceCycle } @@ -222,7 +222,7 @@ func TestSliceNoCycle(t *testing.T) { } } -var unsupportedValues = []interface{}{ +var unsupportedValues = []any{ math.NaN(), math.Inf(-1), math.Inf(1), @@ -367,15 +367,15 @@ func TestMarshalerEscaping(t *testing.T) { func TestAnonymousFields(t *testing.T) { tests := []struct { - label string // Test name - makeInput func() interface{} // Function to create input value - want string // Expected JSON output + label string // Test name + makeInput func() any // Function to create input value + want string // Expected JSON output }{{ // Both S1 and S2 have a field named X. From the perspective of S, // it is ambiguous which one X refers to. // This should not serialize either field. label: "AmbiguousField", - makeInput: func() interface{} { + makeInput: func() any { type ( S1 struct{ x, X int } S2 struct{ x, X int } @@ -391,7 +391,7 @@ func TestAnonymousFields(t *testing.T) { label: "DominantField", // 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. - makeInput: func() interface{} { + makeInput: func() any { type ( S1 struct{ x, X int } S2 struct{ x, X int } @@ -407,7 +407,7 @@ func TestAnonymousFields(t *testing.T) { }, { // Unexported embedded field of non-struct type should not be serialized. label: "UnexportedEmbeddedInt", - makeInput: func() interface{} { + makeInput: func() any { type ( myInt int S struct{ myInt } @@ -418,7 +418,7 @@ func TestAnonymousFields(t *testing.T) { }, { // Exported embedded field of non-struct type should be serialized. label: "ExportedEmbeddedInt", - makeInput: func() interface{} { + makeInput: func() any { type ( MyInt int S struct{ MyInt } @@ -430,7 +430,7 @@ func TestAnonymousFields(t *testing.T) { // Unexported embedded field of pointer to non-struct type // should not be serialized. label: "UnexportedEmbeddedIntPointer", - makeInput: func() interface{} { + makeInput: func() any { type ( myInt int S struct{ *myInt } @@ -444,7 +444,7 @@ func TestAnonymousFields(t *testing.T) { // Exported embedded field of pointer to non-struct type // should be serialized. label: "ExportedEmbeddedIntPointer", - makeInput: func() interface{} { + makeInput: func() any { type ( MyInt int S struct{ *MyInt } @@ -459,7 +459,7 @@ func TestAnonymousFields(t *testing.T) { // exported fields be serialized regardless of whether the struct types // themselves are exported. label: "EmbeddedStruct", - makeInput: func() interface{} { + makeInput: func() any { type ( s1 struct{ x, X int } S2 struct{ y, Y int } @@ -476,7 +476,7 @@ func TestAnonymousFields(t *testing.T) { // exported fields be serialized regardless of whether the struct types // themselves are exported. label: "EmbeddedStructPointer", - makeInput: func() interface{} { + makeInput: func() any { type ( s1 struct{ x, X int } S2 struct{ y, Y int } @@ -492,7 +492,7 @@ func TestAnonymousFields(t *testing.T) { // Exported fields on embedded unexported structs at multiple levels // of nesting should still be serialized. label: "NestedStructAndInts", - makeInput: func() interface{} { + makeInput: func() any { type ( MyInt1 int MyInt2 int @@ -519,7 +519,7 @@ func TestAnonymousFields(t *testing.T) { // the embedded fields behind it. Not properly doing so may // result in the wrong output or reflect panics. label: "EmbeddedFieldBehindNilPointer", - makeInput: func() interface{} { + makeInput: func() any { type ( S2 struct{ Field string } S struct{ *S2 } @@ -589,22 +589,22 @@ func (nm *nilTextMarshaler) MarshalText() ([]byte, error) { // See golang.org/issue/16042 and golang.org/issue/34235. func TestNilMarshal(t *testing.T) { testCases := []struct { - v interface{} + v any want string }{ {v: nil, want: `null`}, {v: new(float64), want: `0`}, - {v: []interface{}(nil), want: `null`}, + {v: []any(nil), want: `null`}, {v: []string(nil), want: `null`}, {v: map[string]string(nil), want: `null`}, {v: []byte(nil), want: `null`}, {v: struct{ M string }{"gopher"}, want: `{"M":"gopher"}`}, {v: struct{ M Marshaler }{}, want: `{"M":null}`}, {v: struct{ M Marshaler }{(*nilJSONMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, - {v: struct{ M interface{} }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`}, + {v: struct{ M any }{(*nilJSONMarshaler)(nil)}, want: `{"M":null}`}, {v: struct{ M encoding.TextMarshaler }{}, want: `{"M":null}`}, {v: struct{ M encoding.TextMarshaler }{(*nilTextMarshaler)(nil)}, want: `{"M":"0zenil0"}`}, - {v: struct{ M interface{} }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`}, + {v: struct{ M any }{(*nilTextMarshaler)(nil)}, want: `{"M":null}`}, } for _, tt := range testCases { @@ -864,7 +864,7 @@ type textint int 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 fmt.Fprintf(&buf, format, a...) return buf.Bytes(), nil @@ -877,7 +877,7 @@ func (f textfloat) MarshalText() ([]byte, error) { return tenc(`TF:%0.2f`, f) } // Issue 13783 func TestEncodeBytekind(t *testing.T) { testdata := []struct { - data interface{} + data any want string }{ {byte(7), "7"}, @@ -966,7 +966,7 @@ func TestMarshalFloat(t *testing.T) { t.Parallel() nfail := 0 test := func(f float64, bits int) { - vf := interface{}(f) + vf := any(f) if bits == 32 { f = float64(float32(f)) // round vf = float32(f) @@ -1062,25 +1062,25 @@ func TestMarshalRawMessageValue(t *testing.T) { ) tests := []struct { - in interface{} + in any want string ok bool }{ // Test with nil RawMessage. {rawNil, "null", true}, {&rawNil, "null", true}, - {[]interface{}{rawNil}, "[null]", true}, - {&[]interface{}{rawNil}, "[null]", true}, - {[]interface{}{&rawNil}, "[null]", true}, - {&[]interface{}{&rawNil}, "[null]", true}, + {[]any{rawNil}, "[null]", true}, + {&[]any{rawNil}, "[null]", true}, + {[]any{&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}, - {map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, - {&map[string]interface{}{"M": rawNil}, `{"M":null}`, true}, - {map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, - {&map[string]interface{}{"M": &rawNil}, `{"M":null}`, true}, + {map[string]any{"M": rawNil}, `{"M":null}`, true}, + {&map[string]any{"M": rawNil}, `{"M":null}`, true}, + {map[string]any{"M": &rawNil}, `{"M":null}`, true}, + {&map[string]any{"M": &rawNil}, `{"M":null}`, true}, {T1{rawNil}, "{}", true}, {T2{&rawNil}, `{"M":null}`, true}, {&T1{rawNil}, "{}", true}, @@ -1089,18 +1089,18 @@ func TestMarshalRawMessageValue(t *testing.T) { // Test with empty, but non-nil, RawMessage. {rawEmpty, "", false}, {&rawEmpty, "", false}, - {[]interface{}{rawEmpty}, "", false}, - {&[]interface{}{rawEmpty}, "", false}, - {[]interface{}{&rawEmpty}, "", false}, - {&[]interface{}{&rawEmpty}, "", false}, + {[]any{rawEmpty}, "", false}, + {&[]any{rawEmpty}, "", false}, + {[]any{&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}, - {map[string]interface{}{"nil": rawEmpty}, "", false}, - {&map[string]interface{}{"nil": rawEmpty}, "", false}, - {map[string]interface{}{"nil": &rawEmpty}, "", false}, - {&map[string]interface{}{"nil": &rawEmpty}, "", false}, + {map[string]any{"nil": rawEmpty}, "", false}, + {&map[string]any{"nil": rawEmpty}, "", false}, + {map[string]any{"nil": &rawEmpty}, "", false}, + {&map[string]any{"nil": &rawEmpty}, "", false}, {T1{rawEmpty}, "{}", true}, {T2{&rawEmpty}, "", false}, {&T1{rawEmpty}, "{}", true}, @@ -1113,18 +1113,18 @@ func TestMarshalRawMessageValue(t *testing.T) { // See https://golang.org/issues/14493#issuecomment-255857318 {rawText, `"foo"`, true}, // Issue6458 {&rawText, `"foo"`, true}, - {[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 - {&[]interface{}{rawText}, `["foo"]`, true}, // Issue6458 - {[]interface{}{&rawText}, `["foo"]`, true}, - {&[]interface{}{&rawText}, `["foo"]`, true}, + {[]any{rawText}, `["foo"]`, true}, // Issue6458 + {&[]any{rawText}, `["foo"]`, true}, // Issue6458 + {[]any{&rawText}, `["foo"]`, true}, + {&[]any{&rawText}, `["foo"]`, true}, {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}, - {map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 - {&map[string]interface{}{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 - {map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, - {&map[string]interface{}{"M": &rawText}, `{"M":"foo"}`, true}, + {map[string]any{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 + {&map[string]any{"M": rawText}, `{"M":"foo"}`, true}, // Issue6458 + {map[string]any{"M": &rawText}, `{"M":"foo"}`, true}, + {&map[string]any{"M": &rawText}, `{"M":"foo"}`, true}, {T1{rawText}, `{"M":"foo"}`, true}, // Issue6458 {T2{&rawText}, `{"M":"foo"}`, true}, {&T1{rawText}, `{"M":"foo"}`, true}, diff --git a/src/encoding/json/example_test.go b/src/encoding/json/example_test.go index fbecf1b593..2261c770c0 100644 --- a/src/encoding/json/example_test.go +++ b/src/encoding/json/example_test.go @@ -200,7 +200,7 @@ func ExampleRawMessage_unmarshal() { } for _, c := range colors { - var dst interface{} + var dst any switch c.Space { case "RGB": dst = new(RGB) diff --git a/src/encoding/json/fuzz.go b/src/encoding/json/fuzz.go index f00898a798..b8f4ff2c1d 100644 --- a/src/encoding/json/fuzz.go +++ b/src/encoding/json/fuzz.go @@ -11,10 +11,10 @@ import ( ) func Fuzz(data []byte) (score int) { - for _, ctor := range []func() interface{}{ - func() interface{} { return new(interface{}) }, - func() interface{} { return new(map[string]interface{}) }, - func() interface{} { return new([]interface{}) }, + for _, ctor := range []func() any{ + func() any { return new(any) }, + func() any { return new(map[string]any) }, + func() any { return new([]any) }, } { v := ctor() err := Unmarshal(data, v) diff --git a/src/encoding/json/scanner.go b/src/encoding/json/scanner.go index 9dc1903e2d..dbaa821bec 100644 --- a/src/encoding/json/scanner.go +++ b/src/encoding/json/scanner.go @@ -83,7 +83,7 @@ type scanner struct { } var scannerPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &scanner{} }, } diff --git a/src/encoding/json/scanner_test.go b/src/encoding/json/scanner_test.go index 3737516a45..3474b3e481 100644 --- a/src/encoding/json/scanner_test.go +++ b/src/encoding/json/scanner_test.go @@ -237,7 +237,7 @@ func initBig() { jsonBig = b } -func genValue(n int) interface{} { +func genValue(n int) any { if n > 1 { switch rand.Intn(2) { case 0: @@ -270,7 +270,7 @@ func genString(stddev float64) string { 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))) if f > n { f = n @@ -278,14 +278,14 @@ func genArray(n int) []interface{} { if f < 1 { f = 1 } - x := make([]interface{}, f) + x := make([]any, f) for i := range x { x[i] = genValue(((i+1)*n)/f - (i*n)/f) } 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))) if f > n { f = n @@ -293,7 +293,7 @@ func genMap(n int) map[string]interface{} { if n > 0 && f == 0 { f = 1 } - x := make(map[string]interface{}) + x := make(map[string]any) for i := 0; i < f; i++ { x[genString(10)] = genValue(((i+1)*n)/f - (i*n)/f) } diff --git a/src/encoding/json/stream.go b/src/encoding/json/stream.go index 81f404f426..6362170d5d 100644 --- a/src/encoding/json/stream.go +++ b/src/encoding/json/stream.go @@ -46,7 +46,7 @@ func (dec *Decoder) DisallowUnknownFields() { dec.d.disallowUnknownFields = true // // See the documentation for Unmarshal for details about // the conversion of JSON into a Go value. -func (dec *Decoder) Decode(v interface{}) error { +func (dec *Decoder) Decode(v any) error { if dec.err != nil { return dec.err } @@ -198,7 +198,7 @@ func NewEncoder(w io.Writer) *Encoder { // // See the documentation for Marshal for details about the // conversion of Go values to JSON. -func (enc *Encoder) Encode(v interface{}) error { +func (enc *Encoder) Encode(v any) error { if enc.err != nil { return enc.err } @@ -288,7 +288,7 @@ var _ Unmarshaler = (*RawMessage)(nil) // string, for JSON string literals // nil, for JSON null // -type Token interface{} +type Token any const ( tokenTopValue = iota @@ -452,7 +452,7 @@ func (dec *Decoder) Token() (Token, error) { if !dec.tokenValueAllowed() { return dec.tokenError(c) } - var x interface{} + var x any if err := dec.Decode(&x); err != nil { return nil, err } diff --git a/src/encoding/json/stream_test.go b/src/encoding/json/stream_test.go index c284f2d965..0e156d98e9 100644 --- a/src/encoding/json/stream_test.go +++ b/src/encoding/json/stream_test.go @@ -18,14 +18,14 @@ import ( // Test values for the stream test. // One of each JSON kind. -var streamTest = []interface{}{ +var streamTest = []any{ 0.1, "hello", nil, true, false, - []interface{}{"a", "b", "c"}, - map[string]interface{}{"K": "Kelvin", "ß": "long s"}, + []any{"a", "b", "c"}, + map[string]any{"K": "Kelvin", "ß": "long s"}, 3.14, // another value to make sure something can follow map } @@ -124,7 +124,7 @@ func TestEncoderSetEscapeHTML(t *testing.T) { for _, tt := range []struct { name string - v interface{} + v any wantEscape string want string }{ @@ -182,7 +182,7 @@ func TestDecoder(t *testing.T) { buf.WriteRune(c) } } - out := make([]interface{}, i) + out := make([]any, i) dec := NewDecoder(&buf) for j := range out { if err := dec.Decode(&out[j]); err != nil { @@ -297,7 +297,7 @@ func TestBlocking(t *testing.T) { for _, enc := range blockingTests { r, w := net.Pipe() go w.Write([]byte(enc)) - var val interface{} + var val any // If Decode reads beyond what w.Write writes above, // it will block, and the test will deadlock. @@ -326,80 +326,80 @@ func BenchmarkEncoderEncode(b *testing.B) { type tokenStreamCase struct { json string - expTokens []interface{} + expTokens []any } type decodeThis struct { - v interface{} + v any } var tokenStreamCases = []tokenStreamCase{ // streaming token cases - {json: `10`, expTokens: []interface{}{float64(10)}}, - {json: ` [10] `, expTokens: []interface{}{ + {json: `10`, expTokens: []any{float64(10)}}, + {json: ` [10] `, expTokens: []any{ Delim('['), float64(10), Delim(']')}}, - {json: ` [false,10,"b"] `, expTokens: []interface{}{ + {json: ` [false,10,"b"] `, expTokens: []any{ Delim('['), false, float64(10), "b", Delim(']')}}, - {json: `{ "a": 1 }`, expTokens: []interface{}{ + {json: `{ "a": 1 }`, expTokens: []any{ Delim('{'), "a", float64(1), Delim('}')}}, - {json: `{"a": 1, "b":"3"}`, expTokens: []interface{}{ + {json: `{"a": 1, "b":"3"}`, expTokens: []any{ Delim('{'), "a", float64(1), "b", "3", Delim('}')}}, - {json: ` [{"a": 1},{"a": 2}] `, expTokens: []interface{}{ + {json: ` [{"a": 1},{"a": 2}] `, expTokens: []any{ Delim('['), Delim('{'), "a", float64(1), Delim('}'), Delim('{'), "a", float64(2), Delim('}'), Delim(']')}}, - {json: `{"obj": {"a": 1}}`, expTokens: []interface{}{ + {json: `{"obj": {"a": 1}}`, expTokens: []any{ Delim('{'), "obj", Delim('{'), "a", float64(1), Delim('}'), Delim('}')}}, - {json: `{"obj": [{"a": 1}]}`, expTokens: []interface{}{ + {json: `{"obj": [{"a": 1}]}`, expTokens: []any{ Delim('{'), "obj", Delim('['), Delim('{'), "a", float64(1), Delim('}'), Delim(']'), Delim('}')}}, // streaming tokens with intermittent Decode() - {json: `{ "a": 1 }`, expTokens: []interface{}{ + {json: `{ "a": 1 }`, expTokens: []any{ Delim('{'), "a", decodeThis{float64(1)}, Delim('}')}}, - {json: ` [ { "a" : 1 } ] `, expTokens: []interface{}{ + {json: ` [ { "a" : 1 } ] `, expTokens: []any{ Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(1)}}, Delim(']')}}, - {json: ` [{"a": 1},{"a": 2}] `, expTokens: []interface{}{ + {json: ` [{"a": 1},{"a": 2}] `, expTokens: []any{ Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, - decodeThis{map[string]interface{}{"a": float64(2)}}, + decodeThis{map[string]any{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(2)}}, Delim(']')}}, - {json: `{ "obj" : [ { "a" : 1 } ] }`, expTokens: []interface{}{ + {json: `{ "obj" : [ { "a" : 1 } ] }`, expTokens: []any{ Delim('{'), "obj", Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(1)}}, Delim(']'), Delim('}')}}, - {json: `{"obj": {"a": 1}}`, expTokens: []interface{}{ + {json: `{"obj": {"a": 1}}`, expTokens: []any{ Delim('{'), "obj", - decodeThis{map[string]interface{}{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(1)}}, Delim('}')}}, - {json: `{"obj": [{"a": 1}]}`, expTokens: []interface{}{ + {json: `{"obj": [{"a": 1}]}`, expTokens: []any{ Delim('{'), "obj", - decodeThis{[]interface{}{ - map[string]interface{}{"a": float64(1)}, + decodeThis{[]any{ + map[string]any{"a": float64(1)}, }}, Delim('}')}}, - {json: ` [{"a": 1} {"a": 2}] `, expTokens: []interface{}{ + {json: ` [{"a": 1} {"a": 2}] `, expTokens: []any{ Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, + decodeThis{map[string]any{"a": float64(1)}}, decodeThis{&SyntaxError{"expected comma after array element", 11}}, }}, - {json: `{ "` + strings.Repeat("a", 513) + `" 1 }`, expTokens: []interface{}{ + {json: `{ "` + strings.Repeat("a", 513) + `" 1 }`, expTokens: []any{ Delim('{'), strings.Repeat("a", 513), decodeThis{&SyntaxError{"expected colon after object key", 518}}, }}, - {json: `{ "\a" }`, expTokens: []interface{}{ + {json: `{ "\a" }`, expTokens: []any{ Delim('{'), &SyntaxError{"invalid character 'a' in string escape code", 3}, }}, - {json: ` \a`, expTokens: []interface{}{ + {json: ` \a`, expTokens: []any{ &SyntaxError{"invalid character '\\\\' looking for beginning of value", 1}, }}, } @@ -410,7 +410,7 @@ func TestDecodeInStream(t *testing.T) { dec := NewDecoder(strings.NewReader(tcase.json)) for i, etk := range tcase.expTokens { - var tk interface{} + var tk any var err error if dt, ok := etk.(decodeThis); ok { diff --git a/src/encoding/json/tagkey_test.go b/src/encoding/json/tagkey_test.go index bbb4e6a28d..6330efd3c2 100644 --- a/src/encoding/json/tagkey_test.go +++ b/src/encoding/json/tagkey_test.go @@ -73,7 +73,7 @@ type unicodeTag struct { } var structTagObjectKeyTests = []struct { - raw interface{} + raw any value string key string }{ @@ -101,12 +101,12 @@ func TestStructTagObjectKey(t *testing.T) { if err != nil { t.Fatalf("Marshal(%#q) failed: %v", tt.raw, err) } - var f interface{} + var f any err = Unmarshal(b, &f) if err != nil { 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 { case tt.key: if s, ok := v.(string); !ok || s != tt.value { diff --git a/src/encoding/xml/marshal.go b/src/encoding/xml/marshal.go index 1f0eb76341..6859be04a2 100644 --- a/src/encoding/xml/marshal.go +++ b/src/encoding/xml/marshal.go @@ -76,7 +76,7 @@ const ( // See MarshalIndent for an example. // // Marshal will return an error if asked to marshal a channel, function, or map. -func Marshal(v interface{}) ([]byte, error) { +func Marshal(v any) ([]byte, error) { var b bytes.Buffer if err := NewEncoder(&b).Encode(v); err != nil { return nil, err @@ -122,7 +122,7 @@ type MarshalerAttr interface { // MarshalIndent works like Marshal, but each XML element begins on a new // indented line that starts with prefix and is followed by one or more // copies of indent according to the nesting depth. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { +func MarshalIndent(v any, prefix, indent string) ([]byte, error) { var b bytes.Buffer enc := NewEncoder(&b) enc.Indent(prefix, indent) @@ -158,7 +158,7 @@ func (enc *Encoder) Indent(prefix, indent string) { // of Go values to XML. // // Encode calls Flush before returning. -func (enc *Encoder) Encode(v interface{}) error { +func (enc *Encoder) Encode(v any) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil) if err != nil { return err @@ -173,7 +173,7 @@ func (enc *Encoder) Encode(v interface{}) error { // of Go values to XML. // // EncodeElement calls Flush before returning. -func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error { +func (enc *Encoder) EncodeElement(v any, start StartElement) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start) if err != nil { return err diff --git a/src/encoding/xml/marshal_test.go b/src/encoding/xml/marshal_test.go index cb95905f5b..5fdbae7ef0 100644 --- a/src/encoding/xml/marshal_test.go +++ b/src/encoding/xml/marshal_test.go @@ -120,17 +120,17 @@ type MixedNested struct { } type NilTest struct { - A interface{} `xml:"parent1>parent2>a"` - B interface{} `xml:"parent1>b"` - C interface{} `xml:"parent1>parent2>c"` + A any `xml:"parent1>parent2>a"` + B any `xml:"parent1>b"` + C any `xml:"parent1>parent2>c"` } type Service struct { XMLName struct{} `xml:"service"` Domain *Domain `xml:"host>domain"` Port *Port `xml:"host>port"` - Extra1 interface{} - Extra2 interface{} `xml:"host>extra2"` + Extra1 any + Extra2 any `xml:"host>extra2"` } var nilStruct *Ship @@ -283,7 +283,7 @@ type Data struct { } type Plain struct { - V interface{} + V any } type MyInt int @@ -387,7 +387,7 @@ type NestedAndCData struct { CDATA string `xml:",cdata"` } -func ifaceptr(x interface{}) interface{} { +func ifaceptr(x any) any { return &x } @@ -412,7 +412,7 @@ type DirectComment struct { type IfaceComment struct { T1 T1 - Comment interface{} `xml:",comment"` + Comment any `xml:",comment"` T2 T2 } @@ -430,7 +430,7 @@ type DirectChardata struct { type IfaceChardata struct { T1 T1 - Chardata interface{} `xml:",chardata"` + Chardata any `xml:",chardata"` T2 T2 } @@ -448,7 +448,7 @@ type DirectCDATA struct { type IfaceCDATA struct { T1 T1 - CDATA interface{} `xml:",cdata"` + CDATA any `xml:",cdata"` T2 T2 } @@ -466,7 +466,7 @@ type DirectInnerXML struct { type IfaceInnerXML struct { T1 T1 - InnerXML interface{} `xml:",innerxml"` + InnerXML any `xml:",innerxml"` T2 T2 } @@ -484,7 +484,7 @@ type DirectElement struct { type IfaceElement struct { T1 T1 - Element interface{} + Element any T2 T2 } @@ -502,7 +502,7 @@ type DirectOmitEmpty struct { type IfaceOmitEmpty struct { T1 T1 - OmitEmpty interface{} `xml:",omitempty"` + OmitEmpty any `xml:",omitempty"` T2 T2 } @@ -520,7 +520,7 @@ type DirectAny struct { type IfaceAny struct { T1 T1 - Any interface{} `xml:",any"` + Any any `xml:",any"` T2 T2 } @@ -540,7 +540,7 @@ var ( // please try to make them two-way as well to ensure that // marshaling and unmarshaling are as symmetrical as feasible. var marshalTests = []struct { - Value interface{} + Value any ExpectXML string MarshalOnly bool MarshalError string @@ -1700,7 +1700,7 @@ type BadAttr struct { } var marshalErrorTests = []struct { - Value interface{} + Value any Err string Kind reflect.Kind }{ @@ -1738,7 +1738,7 @@ var marshalErrorTests = []struct { } var marshalIndentTests = []struct { - Value interface{} + Value any Prefix string Indent string ExpectXML string @@ -1933,7 +1933,7 @@ func BenchmarkUnmarshal(b *testing.B) { func TestStructPointerMarshal(t *testing.T) { type A struct { XMLName string `xml:"a"` - B []interface{} + B []any } type C struct { XMLName Name @@ -2327,7 +2327,7 @@ loop: continue loop } } - errorf := func(f string, a ...interface{}) { + errorf := func(f string, a ...any) { t.Errorf("#%d %s token #%d:%s", i, tt.desc, len(tt.toks)-1, fmt.Sprintf(f, a...)) } switch { diff --git a/src/encoding/xml/read.go b/src/encoding/xml/read.go index 48b0ec055c..0701e18625 100644 --- a/src/encoding/xml/read.go +++ b/src/encoding/xml/read.go @@ -129,13 +129,13 @@ import ( // A missing element or empty attribute value will be unmarshaled as a zero value. // If the field is a slice, a zero value will be appended to the field. Otherwise, the // field will be set to its zero value. -func Unmarshal(data []byte, v interface{}) error { +func Unmarshal(data []byte, v any) error { return NewDecoder(bytes.NewReader(data)).Decode(v) } // Decode works like Unmarshal, except it reads the decoder // stream to find the start element. -func (d *Decoder) Decode(v interface{}) error { +func (d *Decoder) Decode(v any) error { return d.DecodeElement(v, nil) } @@ -143,7 +143,7 @@ func (d *Decoder) Decode(v interface{}) error { // a pointer to the start XML element to decode into v. // It is useful when a client reads some raw XML tokens itself // but also wants to defer to Unmarshal for some elements. -func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error { +func (d *Decoder) DecodeElement(v any, start *StartElement) error { val := reflect.ValueOf(v) if val.Kind() != reflect.Pointer { return errors.New("non-pointer passed to Unmarshal") @@ -188,7 +188,7 @@ type UnmarshalerAttr interface { } // receiverType returns the receiver type to use in an expression like "%s.MethodName". -func receiverType(val interface{}) string { +func receiverType(val any) string { t := reflect.TypeOf(val) if t.Name() != "" { return t.String() diff --git a/src/encoding/xml/read_test.go b/src/encoding/xml/read_test.go index 8c2e70fa22..391fe731a8 100644 --- a/src/encoding/xml/read_test.go +++ b/src/encoding/xml/read_test.go @@ -270,7 +270,7 @@ type PathTestE struct { Before, After string } -var pathTests = []interface{}{ +var pathTests = []any{ &PathTestA{Items: []PathTestItem{{"A"}, {"D"}}, Before: "1", After: "2"}, &PathTestB{Other: []PathTestItem{{"A"}, {"D"}}, Before: "1", After: "2"}, &PathTestC{Values1: []string{"A", "C", "D"}, Values2: []string{"B"}, Before: "1", After: "2"}, @@ -321,7 +321,7 @@ type BadPathEmbeddedB struct { } var badPathTests = []struct { - v, e interface{} + v, e any }{ {&BadPathTestA{}, &TagPathError{reflect.TypeOf(BadPathTestA{}), "First", "items>item1", "Second", "items"}}, {&BadPathTestB{}, &TagPathError{reflect.TypeOf(BadPathTestB{}), "First", "items>item1", "Second", "items>item1>value"}}, @@ -691,7 +691,7 @@ type Pea struct { } type Pod struct { - Pea interface{} `xml:"Pea"` + Pea any `xml:"Pea"` } // https://golang.org/issue/6836 diff --git a/src/encoding/xml/xml.go b/src/encoding/xml/xml.go index 33d0b417b9..8a0a9c253a 100644 --- a/src/encoding/xml/xml.go +++ b/src/encoding/xml/xml.go @@ -52,7 +52,7 @@ type Attr struct { // A Token is an interface holding one of the token types: // StartElement, EndElement, CharData, Comment, ProcInst, or Directive. -type Token interface{} +type Token any // A StartElement represents an XML start element. type StartElement struct { |
