diff --git a/src/archive/tar/common.go b/src/archive/tar/common.go index 595de64725ae6..c99b5c19207f7 100644 --- a/src/archive/tar/common.go +++ b/src/archive/tar/common.go @@ -538,7 +538,7 @@ type headerFileInfo struct { func (fi headerFileInfo) Size() int64 { return fi.h.Size } func (fi headerFileInfo) IsDir() bool { return fi.Mode().IsDir() } func (fi headerFileInfo) ModTime() time.Time { return fi.h.ModTime } -func (fi headerFileInfo) Sys() interface{} { return fi.h } +func (fi headerFileInfo) Sys() any { return fi.h } // Name returns the base name of the file. func (fi headerFileInfo) Name() string { diff --git a/src/archive/tar/reader_test.go b/src/archive/tar/reader_test.go index c31a847ec3e9d..f21a6065b4857 100644 --- a/src/archive/tar/reader_test.go +++ b/src/archive/tar/reader_test.go @@ -1363,7 +1363,7 @@ func TestFileReader(t *testing.T) { wantLCnt int64 wantPCnt int64 } - testFnc interface{} // testRead | testWriteTo | testRemaining + testFnc any // testRead | testWriteTo | testRemaining ) type ( @@ -1376,7 +1376,7 @@ func TestFileReader(t *testing.T) { spd sparseDatas size int64 } - fileMaker interface{} // makeReg | makeSparse + fileMaker any // makeReg | makeSparse ) vectors := []struct { diff --git a/src/archive/tar/tar_test.go b/src/archive/tar/tar_test.go index e9fafc7cc70df..a476f5eb010f2 100644 --- a/src/archive/tar/tar_test.go +++ b/src/archive/tar/tar_test.go @@ -23,7 +23,7 @@ import ( type testError struct{ error } -type fileOps []interface{} // []T where T is (string | int64) +type fileOps []any // []T where T is (string | int64) // testFile is an io.ReadWriteSeeker where the IO operations performed // on it must match the list of operations in ops. diff --git a/src/archive/tar/writer_test.go b/src/archive/tar/writer_test.go index 95ce99a3ed7d1..da3fb89e65e51 100644 --- a/src/archive/tar/writer_test.go +++ b/src/archive/tar/writer_test.go @@ -67,7 +67,7 @@ func TestWriter(t *testing.T) { testClose struct { // Close() == wantErr wantErr error } - testFnc interface{} // testHeader | testWrite | testReadFrom | testClose + testFnc any // testHeader | testWrite | testReadFrom | testClose ) vectors := []struct { @@ -1031,7 +1031,7 @@ func TestFileWriter(t *testing.T) { wantLCnt int64 wantPCnt int64 } - testFnc interface{} // testWrite | testReadFrom | testRemaining + testFnc any // testWrite | testReadFrom | testRemaining ) type ( @@ -1044,7 +1044,7 @@ func TestFileWriter(t *testing.T) { sph sparseHoles size int64 } - fileMaker interface{} // makeReg | makeSparse + fileMaker any // makeReg | makeSparse ) vectors := []struct { diff --git a/src/archive/zip/reader.go b/src/archive/zip/reader.go index 2843a5d6581a5..92fd6f6a92525 100644 --- a/src/archive/zip/reader.go +++ b/src/archive/zip/reader.go @@ -670,7 +670,7 @@ func (f *fileListEntry) Size() int64 { return 0 } func (f *fileListEntry) Mode() fs.FileMode { return fs.ModeDir | 0555 } func (f *fileListEntry) Type() fs.FileMode { return fs.ModeDir } func (f *fileListEntry) IsDir() bool { return true } -func (f *fileListEntry) Sys() interface{} { return nil } +func (f *fileListEntry) Sys() any { return nil } func (f *fileListEntry) ModTime() time.Time { if f.file == nil { diff --git a/src/archive/zip/struct.go b/src/archive/zip/struct.go index 88effedc0f87d..6f73fb8376a85 100644 --- a/src/archive/zip/struct.go +++ b/src/archive/zip/struct.go @@ -163,7 +163,7 @@ func (fi headerFileInfo) ModTime() time.Time { } func (fi headerFileInfo) Mode() fs.FileMode { return fi.fh.Mode() } func (fi headerFileInfo) Type() fs.FileMode { return fi.fh.Mode().Type() } -func (fi headerFileInfo) Sys() interface{} { return fi.fh } +func (fi headerFileInfo) Sys() any { return fi.fh } func (fi headerFileInfo) Info() (fs.FileInfo, error) { return fi, nil } diff --git a/src/builtin/builtin.go b/src/builtin/builtin.go index 9a94c7357d9b5..08ae7ed313add 100644 --- a/src/builtin/builtin.go +++ b/src/builtin/builtin.go @@ -239,7 +239,7 @@ func close(c chan<- Type) // that point, the program is terminated with a non-zero exit code. This // termination sequence is called panicking and can be controlled by the // built-in function recover. -func panic(v interface{}) +func panic(v any) // The recover built-in function allows a program to manage behavior of a // panicking goroutine. Executing a call to recover inside a deferred @@ -250,7 +250,7 @@ func panic(v interface{}) // panicking, or if the argument supplied to panic was nil, recover returns // nil. Thus the return value from recover reports whether the goroutine is // panicking. -func recover() interface{} +func recover() any // The print built-in function formats its arguments in an // implementation-specific way and writes the result to standard error. diff --git a/src/bytes/reader_test.go b/src/bytes/reader_test.go index 8baac5046cbee..9119c944ace47 100644 --- a/src/bytes/reader_test.go +++ b/src/bytes/reader_test.go @@ -76,7 +76,7 @@ func TestReaderAt(t *testing.T) { off int64 n int want string - wanterr interface{} + wanterr any }{ {0, 10, "0123456789", nil}, {1, 10, "123456789", io.EOF}, diff --git a/src/cmd/api/goapi.go b/src/cmd/api/goapi.go index a55e51cc9bc6e..036aefe4d8b3e 100644 --- a/src/cmd/api/goapi.go +++ b/src/cmd/api/goapi.go @@ -1071,7 +1071,7 @@ func (w *Walker) emitMethod(m *types.Selection) { w.emitf("method (%s%s) %s%s", w.typeString(recv), tps, m.Obj().Name(), w.signatureString(sig)) } -func (w *Walker) emitf(format string, args ...interface{}) { +func (w *Walker) emitf(format string, args ...any) { f := strings.Join(w.scope, ", ") + ", " + fmt.Sprintf(format, args...) if strings.Contains(f, "\n") { panic("feature contains newlines: " + f) diff --git a/src/cmd/api/testdata/src/issue21181/p/p_generic.go b/src/cmd/api/testdata/src/issue21181/p/p_generic.go index 4d75809676200..ad6df20187e9c 100644 --- a/src/cmd/api/testdata/src/issue21181/p/p_generic.go +++ b/src/cmd/api/testdata/src/issue21181/p/p_generic.go @@ -1,3 +1,4 @@ +//go:build !amd64 // +build !amd64 package p diff --git a/src/cmd/api/testdata/src/pkg/p1/p1.go b/src/cmd/api/testdata/src/pkg/p1/p1.go index 65181b248a303..81826d768b4f8 100644 --- a/src/cmd/api/testdata/src/pkg/p1/p1.go +++ b/src/cmd/api/testdata/src/pkg/p1/p1.go @@ -197,7 +197,7 @@ var m map[string]int var chanVar chan int -var ifaceVar interface{} = 5 +var ifaceVar any = 5 var assertVar = ifaceVar.(int) diff --git a/src/cmd/api/testdata/src/pkg/p4/p4.go b/src/cmd/api/testdata/src/pkg/p4/p4.go index 462a75be1ad52..1f90e779dd4b5 100644 --- a/src/cmd/api/testdata/src/pkg/p4/p4.go +++ b/src/cmd/api/testdata/src/pkg/p4/p4.go @@ -4,12 +4,12 @@ package p4 -type Pair[T1 interface { M() }, T2 ~int] struct { +type Pair[T1 interface{ M() }, T2 ~int] struct { f1 T1 f2 T2 } -func NewPair[T1 interface { M() }, T2 ~int](v1 T1, v2 T2) Pair[T1, T2] { +func NewPair[T1 interface{ M() }, T2 ~int](v1 T1, v2 T2) Pair[T1, T2] { return Pair[T1, T2]{f1: v1, f2: v2} } diff --git a/src/cmd/compile/internal/importer/gcimporter_test.go b/src/cmd/compile/internal/importer/gcimporter_test.go index e097507f69527..5d80db244b9bf 100644 --- a/src/cmd/compile/internal/importer/gcimporter_test.go +++ b/src/cmd/compile/internal/importer/gcimporter_test.go @@ -258,7 +258,7 @@ var importedObjectTests = []struct { {"go/internal/gcimporter.FindPkg", "func FindPkg(path string, srcDir string) (filename string, id string)"}, // interfaces - {"context.Context", "type Context interface{Deadline() (deadline time.Time, ok bool); Done() <-chan struct{}; Err() error; Value(key interface{}) interface{}}"}, + {"context.Context", "type Context interface{Deadline() (deadline time.Time, ok bool); Done() <-chan struct{}; Err() error; Value(key any) any}"}, {"crypto.Decrypter", "type Decrypter interface{Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error); Public() PublicKey}"}, {"encoding.BinaryMarshaler", "type BinaryMarshaler interface{MarshalBinary() (data []byte, err error)}"}, {"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"}, diff --git a/src/cmd/cover/testdata/test.go b/src/cmd/cover/testdata/test.go index 703fba57a45b4..0e1dbc6194311 100644 --- a/src/cmd/cover/testdata/test.go +++ b/src/cmd/cover/testdata/test.go @@ -151,7 +151,7 @@ func testSwitch() { } func testTypeSwitch() { - var x = []interface{}{1, 2.0, "hi"} + var x = []any{1, 2.0, "hi"} for _, v := range x { switch func() { check(LINE, 3) }(); v.(type) { case int: @@ -215,7 +215,7 @@ func testEmptySwitches() { switch 3 { } check(LINE, 1) - switch i := (interface{})(3).(int); i { + switch i := (any)(3).(int); i { } check(LINE, 1) c := make(chan int) diff --git a/src/cmd/dist/buildtool.go b/src/cmd/dist/buildtool.go index 17538ad5a43e2..036f8c52fa391 100644 --- a/src/cmd/dist/buildtool.go +++ b/src/cmd/dist/buildtool.go @@ -15,6 +15,7 @@ import ( "fmt" "os" "path/filepath" + "regexp" "runtime" "strings" ) @@ -288,7 +289,11 @@ func rewriteBlock%s(b *Block) bool { panic("unused during bootstrap") } } func bootstrapFixImports(srcFile string) string { - lines := strings.SplitAfter(readfile(srcFile), "\n") + text := readfile(srcFile) + if !strings.Contains(srcFile, "/cmd/") && !strings.Contains(srcFile, `\cmd\`) { + text = regexp.MustCompile(`\bany\b`).ReplaceAllString(text, "interface{}") + } + lines := strings.SplitAfter(text, "\n") inBlock := false for i, line := range lines { if strings.HasPrefix(line, "import (") { diff --git a/src/cmd/doc/pkg.go b/src/cmd/doc/pkg.go index 2257c5c0eb6ee..f51efe08af5c1 100644 --- a/src/cmd/doc/pkg.go +++ b/src/cmd/doc/pkg.go @@ -122,7 +122,7 @@ func trim(path, prefix string) (string, bool) { // main do function, so it doesn't cause an exit. Allows testing to work // without running a subprocess. The log prefix will be added when // logged in main; it is not added here. -func (pkg *Package) Fatalf(format string, args ...interface{}) { +func (pkg *Package) Fatalf(format string, args ...any) { panic(PackageError(fmt.Sprintf(format, args...))) } @@ -209,7 +209,7 @@ func parsePackage(writer io.Writer, pkg *build.Package, userPath string) *Packag return p } -func (pkg *Package) Printf(format string, args ...interface{}) { +func (pkg *Package) Printf(format string, args ...any) { fmt.Fprintf(&pkg.buf, format, args...) } @@ -235,7 +235,7 @@ func (pkg *Package) newlines(n int) { // clears the stuff we don't want to print anyway. It's a bit of a magic trick. func (pkg *Package) emit(comment string, node ast.Node) { if node != nil { - var arg interface{} = node + var arg any = node if showSrc { // Need an extra little dance to get internal comments to appear. arg = &printer.CommentedNode{ diff --git a/src/cmd/doc/testdata/nested/ignore.go b/src/cmd/doc/testdata/nested/ignore.go index c497f1b5bc410..5fa811d0a859c 100644 --- a/src/cmd/doc/testdata/nested/ignore.go +++ b/src/cmd/doc/testdata/nested/ignore.go @@ -1,3 +1,4 @@ +//go:build ignore // +build ignore // Ignored package diff --git a/src/cmd/fix/cftype.go b/src/cmd/fix/cftype.go index 3d292bdeba933..27e4088aa9fa7 100644 --- a/src/cmd/fix/cftype.go +++ b/src/cmd/fix/cftype.go @@ -45,8 +45,8 @@ func typefix(f *ast.File, badType func(string) bool) bool { // step 1: Find all the nils with the offending types. // Compute their replacement. - badNils := map[interface{}]ast.Expr{} - walk(f, func(n interface{}) { + badNils := map[any]ast.Expr{} + walk(f, func(n any) { if i, ok := n.(*ast.Ident); ok && i.Name == "nil" && badType(typeof[n]) { badNils[n] = &ast.BasicLit{ValuePos: i.NamePos, Kind: token.INT, Value: "0"} } @@ -58,7 +58,7 @@ func typefix(f *ast.File, badType func(string) bool) bool { if len(badNils) > 0 { exprType := reflect.TypeOf((*ast.Expr)(nil)).Elem() exprSliceType := reflect.TypeOf(([]ast.Expr)(nil)) - walk(f, func(n interface{}) { + walk(f, func(n any) { if n == nil { return } @@ -99,7 +99,7 @@ func typefix(f *ast.File, badType func(string) bool) bool { // Now we need unsafe.Pointer as an intermediate cast. // (*unsafe.Pointer)(x) where x is type *bad -> (*unsafe.Pointer)(unsafe.Pointer(x)) // (*bad.type)(x) where x is type *unsafe.Pointer -> (*bad.type)(unsafe.Pointer(x)) - walk(f, func(n interface{}) { + walk(f, func(n any) { if n == nil { return } diff --git a/src/cmd/fix/fix.go b/src/cmd/fix/fix.go index b9980c17b9ae4..7abdab28a8df2 100644 --- a/src/cmd/fix/fix.go +++ b/src/cmd/fix/fix.go @@ -43,15 +43,15 @@ func register(f fix) { // walk traverses the AST x, calling visit(y) for each node y in the tree but // also with a pointer to each ast.Expr, ast.Stmt, and *ast.BlockStmt, // in a bottom-up traversal. -func walk(x interface{}, visit func(interface{})) { +func walk(x any, visit func(any)) { walkBeforeAfter(x, nop, visit) } -func nop(interface{}) {} +func nop(any) {} // walkBeforeAfter is like walk but calls before(x) before traversing // x's children and after(x) afterward. -func walkBeforeAfter(x interface{}, before, after func(interface{})) { +func walkBeforeAfter(x any, before, after func(any)) { before(x) switch n := x.(type) { @@ -390,7 +390,7 @@ func renameTop(f *ast.File, old, new string) bool { // Rename top-level old to new, both unresolved names // (probably defined in another file) and names that resolve // to a declaration we renamed. - walk(f, func(n interface{}) { + walk(f, func(n any) { id, ok := n.(*ast.Ident) if ok && isTopName(id, old) { id.Name = new diff --git a/src/cmd/fix/gotypes.go b/src/cmd/fix/gotypes.go index 031f85c9cc5c1..6085816ada45c 100644 --- a/src/cmd/fix/gotypes.go +++ b/src/cmd/fix/gotypes.go @@ -36,7 +36,7 @@ func fixGoExact(f *ast.File) bool { // This one is harder because the import name changes. // First find the import spec. var importSpec *ast.ImportSpec - walk(f, func(n interface{}) { + walk(f, func(n any) { if importSpec != nil { return } diff --git a/src/cmd/fix/main.go b/src/cmd/fix/main.go index b5f7b901d66cc..3229b71ec488e 100644 --- a/src/cmd/fix/main.go +++ b/src/cmd/fix/main.go @@ -245,7 +245,7 @@ func processFile(filename string, useStdin bool) error { return os.WriteFile(f.Name(), newSrc, 0) } -func gofmt(n interface{}) string { +func gofmt(n any) string { var gofmtBuf bytes.Buffer if err := format.Node(&gofmtBuf, fset, n); err != nil { return "<" + err.Error() + ">" diff --git a/src/cmd/fix/netipv6zone.go b/src/cmd/fix/netipv6zone.go index 3e502bda07cb9..199fcf5bf5976 100644 --- a/src/cmd/fix/netipv6zone.go +++ b/src/cmd/fix/netipv6zone.go @@ -26,7 +26,7 @@ func netipv6zone(f *ast.File) bool { } fixed := false - walk(f, func(n interface{}) { + walk(f, func(n any) { cl, ok := n.(*ast.CompositeLit) if !ok { return diff --git a/src/cmd/fix/printerconfig.go b/src/cmd/fix/printerconfig.go index 6d93996872811..bad6953196421 100644 --- a/src/cmd/fix/printerconfig.go +++ b/src/cmd/fix/printerconfig.go @@ -23,7 +23,7 @@ func printerconfig(f *ast.File) bool { } fixed := false - walk(f, func(n interface{}) { + walk(f, func(n any) { cl, ok := n.(*ast.CompositeLit) if !ok { return diff --git a/src/cmd/fix/typecheck.go b/src/cmd/fix/typecheck.go index b7ec72e116736..8a18d61bf2748 100644 --- a/src/cmd/fix/typecheck.go +++ b/src/cmd/fix/typecheck.go @@ -142,9 +142,9 @@ func (typ *Type) dot(cfg *TypeConfig, name string) string { // typeof maps AST nodes to type information in gofmt string form. // assign maps type strings to lists of expressions that were assigned // to values of another type that were assigned to that type. -func typecheck(cfg *TypeConfig, f *ast.File) (typeof map[interface{}]string, assign map[string][]interface{}) { - typeof = make(map[interface{}]string) - assign = make(map[string][]interface{}) +func typecheck(cfg *TypeConfig, f *ast.File) (typeof map[any]string, assign map[string][]any) { + typeof = make(map[any]string) + assign = make(map[string][]any) cfg1 := &TypeConfig{} *cfg1 = *cfg // make copy so we can add locally copied := false @@ -296,7 +296,7 @@ func makeExprList(a []*ast.Ident) []ast.Expr { // Typecheck1 is the recursive form of typecheck. // It is like typecheck but adds to the information in typeof // instead of allocating a new map. -func typecheck1(cfg *TypeConfig, f interface{}, typeof map[interface{}]string, assign map[string][]interface{}) { +func typecheck1(cfg *TypeConfig, f any, typeof map[any]string, assign map[string][]any) { // set sets the type of n to typ. // If isDecl is true, n is being declared. set := func(n ast.Expr, typ string, isDecl bool) { @@ -368,7 +368,7 @@ func typecheck1(cfg *TypeConfig, f interface{}, typeof map[interface{}]string, a // the curfn stack. var curfn []*ast.FuncType - before := func(n interface{}) { + before := func(n any) { // push function type on stack switch n := n.(type) { case *ast.FuncDecl: @@ -379,7 +379,7 @@ func typecheck1(cfg *TypeConfig, f interface{}, typeof map[interface{}]string, a } // After is the real type checker. - after := func(n interface{}) { + after := func(n any) { if n == nil { return } diff --git a/src/cmd/go/internal/base/base.go b/src/cmd/go/internal/base/base.go index 954ce47a98993..c2d4e6b258887 100644 --- a/src/cmd/go/internal/base/base.go +++ b/src/cmd/go/internal/base/base.go @@ -117,12 +117,12 @@ func Exit() { os.Exit(exitStatus) } -func Fatalf(format string, args ...interface{}) { +func Fatalf(format string, args ...any) { Errorf(format, args...) Exit() } -func Errorf(format string, args ...interface{}) { +func Errorf(format string, args ...any) { log.Printf(format, args...) SetExitStatus(1) } @@ -151,7 +151,7 @@ func GetExitStatus() int { // Run runs the command, with stdout and stderr // connected to the go command's own stdout and stderr. // If the command fails, Run reports the error using Errorf. -func Run(cmdargs ...interface{}) { +func Run(cmdargs ...any) { cmdline := str.StringList(cmdargs...) if cfg.BuildN || cfg.BuildX { fmt.Printf("%s\n", strings.Join(cmdline, " ")) diff --git a/src/cmd/go/internal/cmdflag/flag.go b/src/cmd/go/internal/cmdflag/flag.go index 8abb7e559f5ab..a634bc1ab8d7e 100644 --- a/src/cmd/go/internal/cmdflag/flag.go +++ b/src/cmd/go/internal/cmdflag/flag.go @@ -92,7 +92,7 @@ func ParseOne(fs *flag.FlagSet, args []string) (f *flag.Flag, remainingArgs []st // Use fs.Set instead of f.Value.Set below so that any subsequent call to // fs.Visit will correctly visit the flags that have been set. - failf := func(format string, a ...interface{}) (*flag.Flag, []string, error) { + failf := func(format string, a ...any) (*flag.Flag, []string, error) { return f, args, fmt.Errorf(format, a...) } diff --git a/src/cmd/go/internal/fsys/fsys.go b/src/cmd/go/internal/fsys/fsys.go index 0b806027e6469..9a1bbf890e119 100644 --- a/src/cmd/go/internal/fsys/fsys.go +++ b/src/cmd/go/internal/fsys/fsys.go @@ -499,7 +499,7 @@ func (f fakeFile) Size() int64 { return f.real.Size() } func (f fakeFile) Mode() fs.FileMode { return f.real.Mode() } func (f fakeFile) ModTime() time.Time { return f.real.ModTime() } func (f fakeFile) IsDir() bool { return f.real.IsDir() } -func (f fakeFile) Sys() interface{} { return f.real.Sys() } +func (f fakeFile) Sys() any { return f.real.Sys() } // missingFile provides an fs.FileInfo for an overlaid file where the // destination file in the overlay doesn't exist. It returns zero values @@ -512,7 +512,7 @@ func (f missingFile) Size() int64 { return 0 } func (f missingFile) Mode() fs.FileMode { return fs.ModeIrregular } func (f missingFile) ModTime() time.Time { return time.Unix(0, 0) } func (f missingFile) IsDir() bool { return false } -func (f missingFile) Sys() interface{} { return nil } +func (f missingFile) Sys() any { return nil } // fakeDir provides an fs.FileInfo implementation for directories that are // implicitly created by overlaid files. Each directory in the @@ -524,7 +524,7 @@ func (f fakeDir) Size() int64 { return 0 } func (f fakeDir) Mode() fs.FileMode { return fs.ModeDir | 0500 } func (f fakeDir) ModTime() time.Time { return time.Unix(0, 0) } func (f fakeDir) IsDir() bool { return true } -func (f fakeDir) Sys() interface{} { return nil } +func (f fakeDir) Sys() any { return nil } // Glob is like filepath.Glob but uses the overlay file system. func Glob(pattern string) (matches []string, err error) { diff --git a/src/cmd/go/internal/generate/generate.go b/src/cmd/go/internal/generate/generate.go index 4c17f42930a3b..54ccfe78f24b6 100644 --- a/src/cmd/go/internal/generate/generate.go +++ b/src/cmd/go/internal/generate/generate.go @@ -408,7 +408,7 @@ var stop = fmt.Errorf("error in generation") // errorf logs an error message prefixed with the file and line number. // It then exits the program (with exit status 1) because generation stops // at the first error. -func (g *Generator) errorf(format string, args ...interface{}) { +func (g *Generator) errorf(format string, args ...any) { fmt.Fprintf(os.Stderr, "%s:%d: %s\n", base.ShortPath(g.path), g.lineNum, fmt.Sprintf(format, args...)) panic(stop) diff --git a/src/cmd/go/internal/help/help.go b/src/cmd/go/internal/help/help.go index 7a730fc8eb8c5..2a07d2423bdd9 100644 --- a/src/cmd/go/internal/help/help.go +++ b/src/cmd/go/internal/help/help.go @@ -162,7 +162,7 @@ func (w *errWriter) Write(b []byte) (int, error) { } // tmpl executes the given template text on data, writing the result to w. -func tmpl(w io.Writer, text string, data interface{}) { +func tmpl(w io.Writer, text string, data any) { t := template.New("top") t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize}) template.Must(t.Parse(text)) diff --git a/src/cmd/go/internal/imports/testdata/android/e.go b/src/cmd/go/internal/imports/testdata/android/e.go index d9b2db769b5f0..f1b9c888c2caf 100644 --- a/src/cmd/go/internal/imports/testdata/android/e.go +++ b/src/cmd/go/internal/imports/testdata/android/e.go @@ -1,3 +1,4 @@ +//go:build android // +build android package android diff --git a/src/cmd/go/internal/imports/testdata/android/f.go b/src/cmd/go/internal/imports/testdata/android/f.go index 281e4dd6b9898..bb0ff7b73f67c 100644 --- a/src/cmd/go/internal/imports/testdata/android/f.go +++ b/src/cmd/go/internal/imports/testdata/android/f.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package android diff --git a/src/cmd/go/internal/imports/testdata/android/g.go b/src/cmd/go/internal/imports/testdata/android/g.go index 66a789c0ada4b..ee19424890a96 100644 --- a/src/cmd/go/internal/imports/testdata/android/g.go +++ b/src/cmd/go/internal/imports/testdata/android/g.go @@ -1,3 +1,4 @@ +//go:build !android // +build !android package android diff --git a/src/cmd/go/internal/imports/testdata/illumos/e.go b/src/cmd/go/internal/imports/testdata/illumos/e.go index 5e1ed3cb9deca..fddf2c429909b 100644 --- a/src/cmd/go/internal/imports/testdata/illumos/e.go +++ b/src/cmd/go/internal/imports/testdata/illumos/e.go @@ -1,3 +1,4 @@ +//go:build illumos // +build illumos package illumos diff --git a/src/cmd/go/internal/imports/testdata/illumos/f.go b/src/cmd/go/internal/imports/testdata/illumos/f.go index f3e3f728bce5d..4b6d528e4c222 100644 --- a/src/cmd/go/internal/imports/testdata/illumos/f.go +++ b/src/cmd/go/internal/imports/testdata/illumos/f.go @@ -1,3 +1,4 @@ +//go:build solaris // +build solaris package illumos diff --git a/src/cmd/go/internal/imports/testdata/illumos/g.go b/src/cmd/go/internal/imports/testdata/illumos/g.go index b30f1eb403732..1bf826b81510b 100644 --- a/src/cmd/go/internal/imports/testdata/illumos/g.go +++ b/src/cmd/go/internal/imports/testdata/illumos/g.go @@ -1,3 +1,4 @@ +//go:build !illumos // +build !illumos package illumos diff --git a/src/cmd/go/internal/imports/testdata/star/x1.go b/src/cmd/go/internal/imports/testdata/star/x1.go index 6a9594aed035e..eaaea979e9dc8 100644 --- a/src/cmd/go/internal/imports/testdata/star/x1.go +++ b/src/cmd/go/internal/imports/testdata/star/x1.go @@ -1,8 +1,5 @@ -// +build blahblh -// +build linux -// +build !linux -// +build windows -// +build darwin +//go:build blahblh && linux && !linux && windows && darwin +// +build blahblh,linux,!linux,windows,darwin package x diff --git a/src/cmd/go/internal/list/list.go b/src/cmd/go/internal/list/list.go index 5ecd384787fec..d9a7078ccf29f 100644 --- a/src/cmd/go/internal/list/list.go +++ b/src/cmd/go/internal/list/list.go @@ -358,9 +358,9 @@ func runList(ctx context.Context, cmd *base.Command, args []string) { } } - var do func(interface{}) + var do func(any) if *listJson { - do = func(x interface{}) { + do = func(x any) { b, err := json.MarshalIndent(x, "", "\t") if err != nil { out.Flush() @@ -386,7 +386,7 @@ func runList(ctx context.Context, cmd *base.Command, args []string) { if err != nil { base.Fatalf("%s", err) } - do = func(x interface{}) { + do = func(x any) { if err := tmpl.Execute(out, x); err != nil { out.Flush() base.Fatalf("%s", err) diff --git a/src/cmd/go/internal/load/pkg.go b/src/cmd/go/internal/load/pkg.go index 589bf9e729f39..a891d601b1d4f 100644 --- a/src/cmd/go/internal/load/pkg.go +++ b/src/cmd/go/internal/load/pkg.go @@ -498,7 +498,7 @@ type importError struct { err error // created with fmt.Errorf } -func ImportErrorf(path, format string, args ...interface{}) ImportPathError { +func ImportErrorf(path, format string, args ...any) ImportPathError { err := &importError{importPath: path, err: fmt.Errorf(format, args...)} if errStr := err.Error(); !strings.Contains(errStr, path) { panic(fmt.Sprintf("path %q not in error %q", path, errStr)) @@ -589,10 +589,10 @@ func ClearPackageCachePartial(args []string) { delete(packageCache, arg) } } - resolvedImportCache.DeleteIf(func(key interface{}) bool { + resolvedImportCache.DeleteIf(func(key any) bool { return shouldDelete[key.(importSpec).path] }) - packageDataCache.DeleteIf(func(key interface{}) bool { + packageDataCache.DeleteIf(func(key any) bool { return shouldDelete[key.(string)] }) } @@ -605,7 +605,7 @@ func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package { p := packageCache[arg] if p != nil { delete(packageCache, arg) - resolvedImportCache.DeleteIf(func(key interface{}) bool { + resolvedImportCache.DeleteIf(func(key any) bool { return key.(importSpec).path == p.ImportPath }) packageDataCache.Delete(p.ImportPath) @@ -817,7 +817,7 @@ func loadPackageData(ctx context.Context, path, parentPath, parentDir, parentRoo parentIsStd: parentIsStd, mode: mode, } - r := resolvedImportCache.Do(importKey, func() interface{} { + r := resolvedImportCache.Do(importKey, func() any { var r resolvedImport if build.IsLocalImport(path) { r.dir = filepath.Join(parentDir, path) @@ -844,7 +844,7 @@ func loadPackageData(ctx context.Context, path, parentPath, parentDir, parentRoo // Load the package from its directory. If we already found the package's // directory when resolving its import path, use that. - data := packageDataCache.Do(r.path, func() interface{} { + data := packageDataCache.Do(r.path, func() any { loaded = true var data packageData if r.dir != "" { @@ -1063,7 +1063,7 @@ func cleanImport(path string) string { var isDirCache par.Cache func isDir(path string) bool { - return isDirCache.Do(path, func() interface{} { + return isDirCache.Do(path, func() any { fi, err := fsys.Stat(path) return err == nil && fi.IsDir() }).(bool) @@ -1191,7 +1191,7 @@ var ( // goModPath returns the module path in the go.mod in dir, if any. func goModPath(dir string) (path string) { - return goModPathCache.Do(dir, func() interface{} { + return goModPathCache.Do(dir, func() any { data, err := os.ReadFile(filepath.Join(dir, "go.mod")) if err != nil { return "" @@ -2221,7 +2221,7 @@ func (p *Package) setBuildInfo() { // executables always appear stale unless the user sets the same flags. // Perhaps it's safe to omit those flags when GO_GCFLAGS and GO_LDFLAGS // are not set? - setPkgErrorf := func(format string, args ...interface{}) { + setPkgErrorf := func(format string, args ...any) { if p.Error == nil { p.Error = &PackageError{Err: fmt.Errorf(format, args...)} } @@ -2397,7 +2397,7 @@ func (p *Package) setBuildInfo() { Status vcs.Status Err error } - cached := vcsStatusCache.Do(repoDir, func() interface{} { + cached := vcsStatusCache.Do(repoDir, func() any { st, err := vcsCmd.Status(vcsCmd, repoDir) return vcsStatusError{st, err} }).(vcsStatusError) diff --git a/src/cmd/go/internal/modcmd/tidy.go b/src/cmd/go/internal/modcmd/tidy.go index 57d303a13c764..d35476eb5393d 100644 --- a/src/cmd/go/internal/modcmd/tidy.go +++ b/src/cmd/go/internal/modcmd/tidy.go @@ -75,8 +75,8 @@ type goVersionFlag struct { v string } -func (f *goVersionFlag) String() string { return f.v } -func (f *goVersionFlag) Get() interface{} { return f.v } +func (f *goVersionFlag) String() string { return f.v } +func (f *goVersionFlag) Get() any { return f.v } func (f *goVersionFlag) Set(s string) error { if s != "" { diff --git a/src/cmd/go/internal/modfetch/cache.go b/src/cmd/go/internal/modfetch/cache.go index 8d299e931af8b..c682447900fbc 100644 --- a/src/cmd/go/internal/modfetch/cache.go +++ b/src/cmd/go/internal/modfetch/cache.go @@ -204,7 +204,7 @@ func (r *cachingRepo) Versions(prefix string) ([]string, error) { list []string err error } - c := r.cache.Do("versions:"+prefix, func() interface{} { + c := r.cache.Do("versions:"+prefix, func() any { list, err := r.repo().Versions(prefix) return cached{list, err} }).(cached) @@ -221,7 +221,7 @@ type cachedInfo struct { } func (r *cachingRepo) Stat(rev string) (*RevInfo, error) { - c := r.cache.Do("stat:"+rev, func() interface{} { + c := r.cache.Do("stat:"+rev, func() any { file, info, err := readDiskStat(r.path, rev) if err == nil { return cachedInfo{info, nil} @@ -233,7 +233,7 @@ func (r *cachingRepo) Stat(rev string) (*RevInfo, error) { // then save the information under the proper version, for future use. if info.Version != rev { file, _ = CachePath(module.Version{Path: r.path, Version: info.Version}, "info") - r.cache.Do("stat:"+info.Version, func() interface{} { + r.cache.Do("stat:"+info.Version, func() any { return cachedInfo{info, err} }) } @@ -253,12 +253,12 @@ func (r *cachingRepo) Stat(rev string) (*RevInfo, error) { } func (r *cachingRepo) Latest() (*RevInfo, error) { - c := r.cache.Do("latest:", func() interface{} { + c := r.cache.Do("latest:", func() any { info, err := r.repo().Latest() // Save info for likely future Stat call. if err == nil { - r.cache.Do("stat:"+info.Version, func() interface{} { + r.cache.Do("stat:"+info.Version, func() any { return cachedInfo{info, err} }) if file, _, err := readDiskStat(r.path, info.Version); err != nil { @@ -281,7 +281,7 @@ func (r *cachingRepo) GoMod(version string) ([]byte, error) { text []byte err error } - c := r.cache.Do("gomod:"+version, func() interface{} { + c := r.cache.Do("gomod:"+version, func() any { file, text, err := readDiskGoMod(r.path, version) if err == nil { // Note: readDiskGoMod already called checkGoMod. diff --git a/src/cmd/go/internal/modfetch/codehost/codehost.go b/src/cmd/go/internal/modfetch/codehost/codehost.go index 5063f8616ab72..4a0e2241e50ac 100644 --- a/src/cmd/go/internal/modfetch/codehost/codehost.go +++ b/src/cmd/go/internal/modfetch/codehost/codehost.go @@ -228,7 +228,7 @@ var dirLock sync.Map // It returns the standard output and, for a non-zero exit, // a *RunError indicating the command, exit status, and standard error. // Standard error is unavailable for commands that exit successfully. -func Run(dir string, cmdline ...interface{}) ([]byte, error) { +func Run(dir string, cmdline ...any) ([]byte, error) { return RunWithStdin(dir, nil, cmdline...) } @@ -236,7 +236,7 @@ func Run(dir string, cmdline ...interface{}) ([]byte, error) { // See https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html. var bashQuoter = strings.NewReplacer(`"`, `\"`, `$`, `\$`, "`", "\\`", `\`, `\\`) -func RunWithStdin(dir string, stdin io.Reader, cmdline ...interface{}) ([]byte, error) { +func RunWithStdin(dir string, stdin io.Reader, cmdline ...any) ([]byte, error) { if dir != "" { muIface, ok := dirLock.Load(dir) if !ok { diff --git a/src/cmd/go/internal/modfetch/codehost/git.go b/src/cmd/go/internal/modfetch/codehost/git.go index 2a5255f115c94..34f453c855ef8 100644 --- a/src/cmd/go/internal/modfetch/codehost/git.go +++ b/src/cmd/go/internal/modfetch/codehost/git.go @@ -56,7 +56,7 @@ func newGitRepoCached(remote string, localOK bool) (Repo, error) { err error } - c := gitRepoCache.Do(key{remote, localOK}, func() interface{} { + c := gitRepoCache.Do(key{remote, localOK}, func() any { repo, err := newGitRepo(remote, localOK) return cached{repo, err} }).(cached) @@ -503,7 +503,7 @@ func (r *gitRepo) Stat(rev string) (*RevInfo, error) { info *RevInfo err error } - c := r.statCache.Do(rev, func() interface{} { + c := r.statCache.Do(rev, func() any { info, err := r.stat(rev) return cached{info, err} }).(cached) diff --git a/src/cmd/go/internal/modfetch/codehost/vcs.go b/src/cmd/go/internal/modfetch/codehost/vcs.go index c8449ccdcc0f2..de62265efc5a7 100644 --- a/src/cmd/go/internal/modfetch/codehost/vcs.go +++ b/src/cmd/go/internal/modfetch/codehost/vcs.go @@ -38,7 +38,7 @@ type VCSError struct { func (e *VCSError) Error() string { return e.Err.Error() } -func vcsErrorf(format string, a ...interface{}) error { +func vcsErrorf(format string, a ...any) error { return &VCSError{Err: fmt.Errorf(format, a...)} } @@ -51,7 +51,7 @@ func NewRepo(vcs, remote string) (Repo, error) { repo Repo err error } - c := vcsRepoCache.Do(key{vcs, remote}, func() interface{} { + c := vcsRepoCache.Do(key{vcs, remote}, func() any { repo, err := newVCSRepo(vcs, remote) if err != nil { err = &VCSError{err} diff --git a/src/cmd/go/internal/modfetch/coderepo.go b/src/cmd/go/internal/modfetch/coderepo.go index df835c3d7e4e0..79da010809b74 100644 --- a/src/cmd/go/internal/modfetch/coderepo.go +++ b/src/cmd/go/internal/modfetch/coderepo.go @@ -321,7 +321,7 @@ func (r *codeRepo) convert(info *codehost.RevInfo, statVers string) (*RevInfo, e return ok } - invalidf := func(format string, args ...interface{}) error { + invalidf := func(format string, args ...any) error { return &module.ModuleError{ Path: r.modPath, Err: &module.InvalidVersionError{ @@ -1066,7 +1066,7 @@ func (fi dataFileInfo) Size() int64 { return int64(len(fi.f.data)) } func (fi dataFileInfo) Mode() fs.FileMode { return 0644 } func (fi dataFileInfo) ModTime() time.Time { return time.Time{} } func (fi dataFileInfo) IsDir() bool { return false } -func (fi dataFileInfo) Sys() interface{} { return nil } +func (fi dataFileInfo) Sys() any { return nil } // hasPathPrefix reports whether the path s begins with the // elements in prefix. diff --git a/src/cmd/go/internal/modfetch/fetch.go b/src/cmd/go/internal/modfetch/fetch.go index e246c1a04dbbf..12b7431570930 100644 --- a/src/cmd/go/internal/modfetch/fetch.go +++ b/src/cmd/go/internal/modfetch/fetch.go @@ -48,7 +48,7 @@ func Download(ctx context.Context, mod module.Version) (dir string, err error) { dir string err error } - c := downloadCache.Do(mod, func() interface{} { + c := downloadCache.Do(mod, func() any { dir, err := download(ctx, mod) if err != nil { return cached{"", err} @@ -165,7 +165,7 @@ func DownloadZip(ctx context.Context, mod module.Version) (zipfile string, err e zipfile string err error } - c := downloadZipCache.Do(mod, func() interface{} { + c := downloadZipCache.Do(mod, func() any { zipfile, err := CachePath(mod, "zip") if err != nil { return cached{"", err} diff --git a/src/cmd/go/internal/modfetch/repo.go b/src/cmd/go/internal/modfetch/repo.go index 0bffa55af6f2e..1b42ecb6edb45 100644 --- a/src/cmd/go/internal/modfetch/repo.go +++ b/src/cmd/go/internal/modfetch/repo.go @@ -196,7 +196,7 @@ func Lookup(proxy, path string) Repo { type cached struct { r Repo } - c := lookupCache.Do(lookupCacheKey{proxy, path}, func() interface{} { + c := lookupCache.Do(lookupCacheKey{proxy, path}, func() any { r := newCachingRepo(path, func() (Repo, error) { r, err := lookup(proxy, path) if err == nil && traceRepo { @@ -308,7 +308,7 @@ func newLoggingRepo(r Repo) *loggingRepo { // defer logCall("hello %s", arg)() // // Note the final (). -func logCall(format string, args ...interface{}) func() { +func logCall(format string, args ...any) func() { start := time.Now() fmt.Fprintf(os.Stderr, "+++ %s\n", fmt.Sprintf(format, args...)) return func() { @@ -371,7 +371,7 @@ type notExistError struct { err error } -func notExistErrorf(format string, args ...interface{}) error { +func notExistErrorf(format string, args ...any) error { return notExistError{fmt.Errorf(format, args...)} } diff --git a/src/cmd/go/internal/modget/get.go b/src/cmd/go/internal/modget/get.go index 893cc92e39990..3d8463e892c69 100644 --- a/src/cmd/go/internal/modget/get.go +++ b/src/cmd/go/internal/modget/get.go @@ -601,7 +601,7 @@ func (r *resolver) matchInModule(ctx context.Context, pattern string, m module.V err error } - e := r.matchInModuleCache.Do(key{pattern, m}, func() interface{} { + e := r.matchInModuleCache.Do(key{pattern, m}, func() any { match := modload.MatchInModule(ctx, pattern, m, imports.AnyTags()) if len(match.Errs) > 0 { return entry{match.Pkgs, match.Errs[0]} @@ -893,7 +893,7 @@ func (r *resolver) checkWildcardVersions(ctx context.Context) { // curM at its original version contains a path matching q.pattern, // but at rev.Version it does not, so (somewhat paradoxically) if // we changed the version of curM it would no longer match the query. - var version interface{} = m + var version any = m if rev.Version != q.version { version = fmt.Sprintf("%s@%s (%s)", m.Path, q.version, m.Version) } diff --git a/src/cmd/go/internal/modload/buildlist.go b/src/cmd/go/internal/modload/buildlist.go index 4ce71fef5b833..45be51f1c649c 100644 --- a/src/cmd/go/internal/modload/buildlist.go +++ b/src/cmd/go/internal/modload/buildlist.go @@ -326,7 +326,7 @@ func readModGraph(ctx context.Context, pruning modPruning, roots []module.Versio // It does not load the transitive requirements of m even if the go version in // m's go.mod file indicates that it supports graph pruning. loadOne := func(m module.Version) (*modFileSummary, error) { - cached := mg.loadCache.Do(m, func() interface{} { + cached := mg.loadCache.Do(m, func() any { summary, err := goModSummary(m) mu.Lock() diff --git a/src/cmd/go/internal/modload/import.go b/src/cmd/go/internal/modload/import.go index bc2b0a0230582..812e48a1568f1 100644 --- a/src/cmd/go/internal/modload/import.go +++ b/src/cmd/go/internal/modload/import.go @@ -612,7 +612,7 @@ func dirInModule(path, mpath, mdir string, isLocal bool) (dir string, haveGoFile // (the main module, and any directory trees pointed at by replace directives). if isLocal { for d := dir; d != mdir && len(d) > len(mdir); { - haveGoMod := haveGoModCache.Do(d, func() interface{} { + haveGoMod := haveGoModCache.Do(d, func() any { fi, err := fsys.Stat(filepath.Join(d, "go.mod")) return err == nil && !fi.IsDir() }).(bool) @@ -635,7 +635,7 @@ func dirInModule(path, mpath, mdir string, isLocal bool) (dir string, haveGoFile // Are there Go source files in the directory? // We don't care about build tags, not even "+build ignore". // We're just looking for a plausible directory. - res := haveGoFilesCache.Do(dir, func() interface{} { + res := haveGoFilesCache.Do(dir, func() any { ok, err := fsys.IsDirWithGoFiles(dir) return goFilesEntry{haveGoFiles: ok, err: err} }).(goFilesEntry) diff --git a/src/cmd/go/internal/modload/load.go b/src/cmd/go/internal/modload/load.go index 5e7075da4ecb1..617b634d263e3 100644 --- a/src/cmd/go/internal/modload/load.go +++ b/src/cmd/go/internal/modload/load.go @@ -859,7 +859,7 @@ func (ld *loader) reset() { // errorf reports an error via either os.Stderr or base.Errorf, // according to whether ld.AllowErrors is set. -func (ld *loader) errorf(format string, args ...interface{}) { +func (ld *loader) errorf(format string, args ...any) { if ld.AllowErrors { fmt.Fprintf(os.Stderr, format, args...) } else { @@ -1492,7 +1492,7 @@ func (ld *loader) pkg(ctx context.Context, path string, flags loadPkgFlags) *loa panic("internal error: (*loader).pkg called with pkgImportsLoaded flag set") } - pkg := ld.pkgCache.Do(path, func() interface{} { + pkg := ld.pkgCache.Do(path, func() any { pkg := &loadPkg{ path: path, } diff --git a/src/cmd/go/internal/modload/modfile.go b/src/cmd/go/internal/modload/modfile.go index 40e6ed787da8b..ec3f57ae3e1da 100644 --- a/src/cmd/go/internal/modload/modfile.go +++ b/src/cmd/go/internal/modload/modfile.go @@ -664,7 +664,7 @@ func rawGoModSummary(m module.Version) (*modFileSummary, error) { summary *modFileSummary err error } - c := rawGoModSummaryCache.Do(key{m}, func() interface{} { + c := rawGoModSummaryCache.Do(key{m}, func() any { summary := new(modFileSummary) name, data, err := rawGoModData(m) if err != nil { @@ -766,7 +766,7 @@ func queryLatestVersionIgnoringRetractions(ctx context.Context, path string) (la latest module.Version err error } - e := latestVersionIgnoringRetractionsCache.Do(path, func() interface{} { + e := latestVersionIgnoringRetractionsCache.Do(path, func() any { ctx, span := trace.StartSpan(ctx, "queryLatestVersionIgnoringRetractions "+path) defer span.Done() diff --git a/src/cmd/go/internal/modload/vendor.go b/src/cmd/go/internal/modload/vendor.go index a735cad90561b..5ea82a862083f 100644 --- a/src/cmd/go/internal/modload/vendor.go +++ b/src/cmd/go/internal/modload/vendor.go @@ -147,7 +147,7 @@ func checkVendorConsistency(index *modFileIndex, modFile *modfile.File) { } vendErrors := new(strings.Builder) - vendErrorf := func(mod module.Version, format string, args ...interface{}) { + vendErrorf := func(mod module.Version, format string, args ...any) { detail := fmt.Sprintf(format, args...) if mod.Version == "" { fmt.Fprintf(vendErrors, "\n\t%s: %s", mod.Path, detail) diff --git a/src/cmd/go/internal/mvs/mvs.go b/src/cmd/go/internal/mvs/mvs.go index 566fa4b6b3903..d25d447b0ee39 100644 --- a/src/cmd/go/internal/mvs/mvs.go +++ b/src/cmd/go/internal/mvs/mvs.go @@ -114,7 +114,7 @@ func buildList(targets []module.Version, reqs Reqs, upgrade func(module.Version) for _, target := range targets { work.Add(target) } - work.Do(10, func(item interface{}) { + work.Do(10, func(item any) { m := item.(module.Version) var required []module.Version diff --git a/src/cmd/go/internal/par/work.go b/src/cmd/go/internal/par/work.go index 960cec6fb1699..496c41b150928 100644 --- a/src/cmd/go/internal/par/work.go +++ b/src/cmd/go/internal/par/work.go @@ -14,24 +14,24 @@ import ( // Work manages a set of work items to be executed in parallel, at most once each. // The items in the set must all be valid map keys. type Work struct { - f func(interface{}) // function to run for each item - running int // total number of runners + f func(any) // function to run for each item + running int // total number of runners mu sync.Mutex - added map[interface{}]bool // items added to set - todo []interface{} // items yet to be run - wait sync.Cond // wait when todo is empty - waiting int // number of runners waiting for todo + added map[any]bool // items added to set + todo []any // items yet to be run + wait sync.Cond // wait when todo is empty + waiting int // number of runners waiting for todo } func (w *Work) init() { if w.added == nil { - w.added = make(map[interface{}]bool) + w.added = make(map[any]bool) } } // Add adds item to the work set, if it hasn't already been added. -func (w *Work) Add(item interface{}) { +func (w *Work) Add(item any) { w.mu.Lock() w.init() if !w.added[item] { @@ -51,7 +51,7 @@ func (w *Work) Add(item interface{}) { // before calling Do (or else Do returns immediately), // but it is allowed for f(item) to add new items to the set. // Do should only be used once on a given Work. -func (w *Work) Do(n int, f func(item interface{})) { +func (w *Work) Do(n int, f func(item any)) { if n < 1 { panic("par.Work.Do: n < 1") } @@ -110,13 +110,13 @@ type Cache struct { type cacheEntry struct { done uint32 mu sync.Mutex - result interface{} + result any } // Do calls the function f if and only if Do is being called for the first time with this key. // No call to Do with a given key returns until the one call to f returns. // Do returns the value returned by the one call to f. -func (c *Cache) Do(key interface{}, f func() interface{}) interface{} { +func (c *Cache) Do(key any, f func() any) any { entryIface, ok := c.m.Load(key) if !ok { entryIface, _ = c.m.LoadOrStore(key, new(cacheEntry)) @@ -136,7 +136,7 @@ func (c *Cache) Do(key interface{}, f func() interface{}) interface{} { // Get returns the cached result associated with key. // It returns nil if there is no such result. // If the result for key is being computed, Get does not wait for the computation to finish. -func (c *Cache) Get(key interface{}) interface{} { +func (c *Cache) Get(key any) any { entryIface, ok := c.m.Load(key) if !ok { return nil @@ -156,7 +156,7 @@ func (c *Cache) Get(key interface{}) interface{} { // TODO(jayconrod): Delete this after the package cache clearing functions // in internal/load have been removed. func (c *Cache) Clear() { - c.m.Range(func(key, value interface{}) bool { + c.m.Range(func(key, value any) bool { c.m.Delete(key) return true }) @@ -169,7 +169,7 @@ func (c *Cache) Clear() { // // TODO(jayconrod): Delete this after the package cache clearing functions // in internal/load have been removed. -func (c *Cache) Delete(key interface{}) { +func (c *Cache) Delete(key any) { c.m.Delete(key) } @@ -180,8 +180,8 @@ func (c *Cache) Delete(key interface{}) { // // TODO(jayconrod): Delete this after the package cache clearing functions // in internal/load have been removed. -func (c *Cache) DeleteIf(pred func(key interface{}) bool) { - c.m.Range(func(key, _ interface{}) bool { +func (c *Cache) DeleteIf(pred func(key any) bool) { + c.m.Range(func(key, _ any) bool { if pred(key) { c.Delete(key) } diff --git a/src/cmd/go/internal/par/work_test.go b/src/cmd/go/internal/par/work_test.go index f104bc4106f20..add0e640d8c09 100644 --- a/src/cmd/go/internal/par/work_test.go +++ b/src/cmd/go/internal/par/work_test.go @@ -16,7 +16,7 @@ func TestWork(t *testing.T) { const N = 10000 n := int32(0) w.Add(N) - w.Do(100, func(x interface{}) { + w.Do(100, func(x any) { atomic.AddInt32(&n, 1) i := x.(int) if i >= 2 { @@ -40,7 +40,7 @@ func TestWorkParallel(t *testing.T) { } start := time.Now() var n int32 - w.Do(N, func(x interface{}) { + w.Do(N, func(x any) { time.Sleep(1 * time.Millisecond) atomic.AddInt32(&n, +1) }) @@ -58,19 +58,19 @@ func TestCache(t *testing.T) { var cache Cache n := 1 - v := cache.Do(1, func() interface{} { n++; return n }) + v := cache.Do(1, func() any { n++; return n }) if v != 2 { t.Fatalf("cache.Do(1) did not run f") } - v = cache.Do(1, func() interface{} { n++; return n }) + v = cache.Do(1, func() any { n++; return n }) if v != 2 { t.Fatalf("cache.Do(1) ran f again!") } - v = cache.Do(2, func() interface{} { n++; return n }) + v = cache.Do(2, func() any { n++; return n }) if v != 3 { t.Fatalf("cache.Do(2) did not run f") } - v = cache.Do(1, func() interface{} { n++; return n }) + v = cache.Do(1, func() any { n++; return n }) if v != 2 { t.Fatalf("cache.Do(1) did not returned saved value from original cache.Do(1)") } diff --git a/src/cmd/go/internal/run/run.go b/src/cmd/go/internal/run/run.go index 878cee367edca..c4b70b64fe651 100644 --- a/src/cmd/go/internal/run/run.go +++ b/src/cmd/go/internal/run/run.go @@ -69,7 +69,7 @@ func init() { CmdRun.Flag.Var((*base.StringsFlag)(&work.ExecCmd), "exec", "") } -func printStderr(args ...interface{}) (int, error) { +func printStderr(args ...any) (int, error) { return fmt.Fprint(os.Stderr, args...) } diff --git a/src/cmd/go/internal/str/str.go b/src/cmd/go/internal/str/str.go index 5bc521b9df468..021bfbff77916 100644 --- a/src/cmd/go/internal/str/str.go +++ b/src/cmd/go/internal/str/str.go @@ -14,7 +14,7 @@ import ( // StringList flattens its arguments into a single []string. // Each argument in args must have type string or []string. -func StringList(args ...interface{}) []string { +func StringList(args ...any) []string { var x []string for _, arg := range args { switch arg := arg.(type) { diff --git a/src/cmd/go/internal/vcs/vcs.go b/src/cmd/go/internal/vcs/vcs.go index 77a75fd51c317..313dc62b780e6 100644 --- a/src/cmd/go/internal/vcs/vcs.go +++ b/src/cmd/go/internal/vcs/vcs.go @@ -1311,7 +1311,7 @@ func metaImportsForPrefix(importPrefix string, mod ModuleMode, security web.Secu return res, nil } - resi, _, _ := fetchGroup.Do(importPrefix, func() (resi interface{}, err error) { + resi, _, _ := fetchGroup.Do(importPrefix, func() (resi any, err error) { fetchCacheMu.Lock() if res, ok := fetchCache[importPrefix]; ok { fetchCacheMu.Unlock() @@ -1588,7 +1588,7 @@ type importError struct { err error } -func importErrorf(path, format string, args ...interface{}) error { +func importErrorf(path, format string, args ...any) error { err := &importError{importPath: path, err: fmt.Errorf(format, args...)} if errStr := err.Error(); !strings.Contains(errStr, path) { panic(fmt.Sprintf("path %q not in error %q", path, errStr)) diff --git a/src/cmd/go/internal/work/action.go b/src/cmd/go/internal/work/action.go index 6f5ac1364cc90..c0862c5efe503 100644 --- a/src/cmd/go/internal/work/action.go +++ b/src/cmd/go/internal/work/action.go @@ -37,7 +37,7 @@ type Builder struct { actionCache map[cacheKey]*Action // a cache of already-constructed actions mkdirCache map[string]bool // a cache of created directories flagCache map[[2]string]bool // a cache of supported compiler flags - Print func(args ...interface{}) (int, error) + Print func(args ...any) (int, error) IsCmdList bool // running as part of go list; set p.Stale and additional fields below NeedError bool // list needs p.Error @@ -120,8 +120,8 @@ type actionQueue []*Action func (q *actionQueue) Len() int { return len(*q) } func (q *actionQueue) Swap(i, j int) { (*q)[i], (*q)[j] = (*q)[j], (*q)[i] } func (q *actionQueue) Less(i, j int) bool { return (*q)[i].priority < (*q)[j].priority } -func (q *actionQueue) Push(x interface{}) { *q = append(*q, x.(*Action)) } -func (q *actionQueue) Pop() interface{} { +func (q *actionQueue) Push(x any) { *q = append(*q, x.(*Action)) } +func (q *actionQueue) Pop() any { n := len(*q) - 1 x := (*q)[n] *q = (*q)[:n] @@ -241,7 +241,7 @@ const ( ) func (b *Builder) Init() { - b.Print = func(a ...interface{}) (int, error) { + b.Print = func(a ...any) (int, error) { return fmt.Fprint(os.Stderr, a...) } b.actionCache = make(map[cacheKey]*Action) diff --git a/src/cmd/go/internal/work/build_test.go b/src/cmd/go/internal/work/build_test.go index 600fc3083f0d5..0b6b83a706cd4 100644 --- a/src/cmd/go/internal/work/build_test.go +++ b/src/cmd/go/internal/work/build_test.go @@ -234,7 +234,7 @@ func TestRespectSetgidDir(t *testing.T) { // of `(*Builder).ShowCmd` afterwards as a sanity check. cfg.BuildX = true var cmdBuf bytes.Buffer - b.Print = func(a ...interface{}) (int, error) { + b.Print = func(a ...any) (int, error) { return cmdBuf.WriteString(fmt.Sprint(a...)) } diff --git a/src/cmd/go/internal/work/exec.go b/src/cmd/go/internal/work/exec.go index 2c040b8ff43fc..ccd5aee221bd0 100644 --- a/src/cmd/go/internal/work/exec.go +++ b/src/cmd/go/internal/work/exec.go @@ -1948,7 +1948,7 @@ func mayberemovefile(s string) { // fmtcmd replaces the name of the current directory with dot (.) // but only when it is at the beginning of a space-separated token. // -func (b *Builder) fmtcmd(dir string, format string, args ...interface{}) string { +func (b *Builder) fmtcmd(dir string, format string, args ...any) string { cmd := fmt.Sprintf(format, args...) if dir != "" && dir != "/" { dot := " ." @@ -1974,7 +1974,7 @@ func (b *Builder) fmtcmd(dir string, format string, args ...interface{}) string // showcmd prints the given command to standard output // for the implementation of -n or -x. -func (b *Builder) Showcmd(dir string, format string, args ...interface{}) { +func (b *Builder) Showcmd(dir string, format string, args ...any) { b.output.Lock() defer b.output.Unlock() b.Print(b.fmtcmd(dir, format, args...) + "\n") @@ -2038,7 +2038,7 @@ var cgoTypeSigRe = lazyregexp.New(`\b_C2?(type|func|var|macro)_\B`) // run runs the command given by cmdline in the directory dir. // If the command fails, run prints information about the failure // and returns a non-nil error. -func (b *Builder) run(a *Action, dir string, desc string, env []string, cmdargs ...interface{}) error { +func (b *Builder) run(a *Action, dir string, desc string, env []string, cmdargs ...any) error { out, err := b.runOut(a, dir, env, cmdargs...) if len(out) > 0 { if desc == "" { @@ -2072,7 +2072,7 @@ func (b *Builder) processOutput(out []byte) string { // runOut runs the command given by cmdline in the directory dir. // It returns the command output and any errors that occurred. // It accumulates execution time in a. -func (b *Builder) runOut(a *Action, dir string, env []string, cmdargs ...interface{}) ([]byte, error) { +func (b *Builder) runOut(a *Action, dir string, env []string, cmdargs ...any) ([]byte, error) { cmdline := str.StringList(cmdargs...) for _, arg := range cmdline { @@ -2409,7 +2409,7 @@ func (b *Builder) gccld(a *Action, p *load.Package, objdir, outfile string, flag cmd = b.GccCmd(p.Dir, objdir) } - cmdargs := []interface{}{cmd, "-o", outfile, objs, flags} + cmdargs := []any{cmd, "-o", outfile, objs, flags} dir := p.Dir out, err := b.runOut(a, base.Cwd(), b.cCompilerEnv(), cmdargs...) diff --git a/src/cmd/go/internal/work/gc.go b/src/cmd/go/internal/work/gc.go index e3b4a817e782c..40175324d2654 100644 --- a/src/cmd/go/internal/work/gc.go +++ b/src/cmd/go/internal/work/gc.go @@ -165,7 +165,7 @@ func (gcToolchain) gc(b *Builder, a *Action, archive string, importcfg, embedcfg gcflags = append(gcflags, fmt.Sprintf("-c=%d", c)) } - args := []interface{}{cfg.BuildToolexec, base.Tool("compile"), "-o", ofile, "-trimpath", a.trimpath(), defaultGcFlags, gcflags} + args := []any{cfg.BuildToolexec, base.Tool("compile"), "-o", ofile, "-trimpath", a.trimpath(), defaultGcFlags, gcflags} if p.Internal.LocalPrefix == "" { args = append(args, "-nolocalimports") } else { @@ -362,11 +362,11 @@ func (a *Action) trimpath() string { return rewrite } -func asmArgs(a *Action, p *load.Package) []interface{} { +func asmArgs(a *Action, p *load.Package) []any { // Add -I pkg/GOOS_GOARCH so #include "textflag.h" works in .s files. inc := filepath.Join(cfg.GOROOT, "pkg", "include") pkgpath := pkgPath(a) - args := []interface{}{cfg.BuildToolexec, base.Tool("asm"), "-p", pkgpath, "-trimpath", a.trimpath(), "-I", a.Objdir, "-I", inc, "-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch, forcedAsmflags, p.Internal.Asmflags} + args := []any{cfg.BuildToolexec, base.Tool("asm"), "-p", pkgpath, "-trimpath", a.trimpath(), "-I", a.Objdir, "-I", inc, "-D", "GOOS_" + cfg.Goos, "-D", "GOARCH_" + cfg.Goarch, forcedAsmflags, p.Internal.Asmflags} if p.ImportPath == "runtime" && cfg.Goarch == "386" { for _, arg := range forcedAsmflags { if arg == "-dynlink" { @@ -455,8 +455,8 @@ func (gcToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, erro // toolVerify checks that the command line args writes the same output file // if run using newTool instead. // Unused now but kept around for future use. -func toolVerify(a *Action, b *Builder, p *load.Package, newTool string, ofile string, args []interface{}) error { - newArgs := make([]interface{}, len(args)) +func toolVerify(a *Action, b *Builder, p *load.Package, newTool string, ofile string, args []any) error { + newArgs := make([]any, len(args)) copy(newArgs, args) newArgs[1] = base.Tool(newTool) newArgs[3] = ofile + ".new" // x.6 becomes x.6.new diff --git a/src/cmd/go/proxy_test.go b/src/cmd/go/proxy_test.go index a387fe67dbfc8..517a88554282d 100644 --- a/src/cmd/go/proxy_test.go +++ b/src/cmd/go/proxy_test.go @@ -357,7 +357,7 @@ func proxyHandler(w http.ResponseWriter, r *http.Request) { zip []byte err error } - c := zipCache.Do(a, func() interface{} { + c := zipCache.Do(a, func() any { var buf bytes.Buffer z := zip.NewWriter(&buf) for _, f := range a.Files { @@ -431,7 +431,7 @@ func readArchive(path, vers string) (*txtar.Archive, error) { prefix := strings.ReplaceAll(enc, "/", "_") name := filepath.Join(cmdGoDir, "testdata/mod", prefix+"_"+encVers+".txt") - a := archiveCache.Do(name, func() interface{} { + a := archiveCache.Do(name, func() any { a, err := txtar.ParseFile(name) if err != nil { if testing.Verbose() || !os.IsNotExist(err) { diff --git a/src/cmd/go/script_test.go b/src/cmd/go/script_test.go index 101195fc9d80e..dbfba2291c44d 100644 --- a/src/cmd/go/script_test.go +++ b/src/cmd/go/script_test.go @@ -375,7 +375,7 @@ Script: default: if strings.HasPrefix(cond.tag, "exec:") { prog := cond.tag[len("exec:"):] - ok = execCache.Do(prog, func() interface{} { + ok = execCache.Do(prog, func() any { if runtime.GOOS == "plan9" && prog == "git" { // The Git command is usually not the real Git on Plan 9. // See https://golang.org/issues/29640. @@ -1310,7 +1310,7 @@ func (ts *testScript) expand(s string, inRegexp bool) string { } // fatalf aborts the test with the given failure message. -func (ts *testScript) fatalf(format string, args ...interface{}) { +func (ts *testScript) fatalf(format string, args ...any) { fmt.Fprintf(&ts.log, "FAIL: %s:%d: %s\n", ts.file, ts.lineno, fmt.Sprintf(format, args...)) ts.t.FailNow() } diff --git a/src/cmd/go/testdata/addmod.go b/src/cmd/go/testdata/addmod.go index a1ace4ce5907e..eac2a7ad449a2 100644 --- a/src/cmd/go/testdata/addmod.go +++ b/src/cmd/go/testdata/addmod.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build ignore // +build ignore // Addmod adds a module as a txtar archive to the testdata/mod directory. @@ -39,7 +40,7 @@ func usage() { var tmpdir string -func fatalf(format string, args ...interface{}) { +func fatalf(format string, args ...any) { os.RemoveAll(tmpdir) log.Fatalf(format, args...) } diff --git a/src/cmd/go/testdata/savedir.go b/src/cmd/go/testdata/savedir.go index 6a8a232702f55..53c78cfb00bba 100644 --- a/src/cmd/go/testdata/savedir.go +++ b/src/cmd/go/testdata/savedir.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build ignore // +build ignore // Savedir archives a directory tree as a txtar archive printed to standard output. diff --git a/src/cmd/go/testdata/testterminal18153/terminal_test.go b/src/cmd/go/testdata/testterminal18153/terminal_test.go index 71493efe98374..34ee580c0e997 100644 --- a/src/cmd/go/testdata/testterminal18153/terminal_test.go +++ b/src/cmd/go/testdata/testterminal18153/terminal_test.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build linux // +build linux // This test is run by src/cmd/dist/test.go (cmd_go_test_terminal), diff --git a/src/cmd/gofmt/gofmt.go b/src/cmd/gofmt/gofmt.go index 860d77aaf0408..51f6e652d9ae9 100644 --- a/src/cmd/gofmt/gofmt.go +++ b/src/cmd/gofmt/gofmt.go @@ -183,7 +183,7 @@ func (r *reporter) getState() *reporterState { // Warnf emits a warning message to the reporter's error stream, // without changing its exit code. -func (r *reporter) Warnf(format string, args ...interface{}) { +func (r *reporter) Warnf(format string, args ...any) { fmt.Fprintf(r.getState().err, format, args...) } diff --git a/src/cmd/internal/buildid/buildid_test.go b/src/cmd/internal/buildid/buildid_test.go index 4895a49e1118a..f04e328046c0a 100644 --- a/src/cmd/internal/buildid/buildid_test.go +++ b/src/cmd/internal/buildid/buildid_test.go @@ -103,7 +103,7 @@ func TestFindAndHash(t *testing.T) { id[i] = byte(i) } numError := 0 - errorf := func(msg string, args ...interface{}) { + errorf := func(msg string, args ...any) { t.Errorf(msg, args...) if numError++; numError > 20 { t.Logf("stopping after too many errors") diff --git a/src/cmd/internal/buildid/rewrite.go b/src/cmd/internal/buildid/rewrite.go index 8814950db0d83..becc0782424ea 100644 --- a/src/cmd/internal/buildid/rewrite.go +++ b/src/cmd/internal/buildid/rewrite.go @@ -151,7 +151,7 @@ func (r *excludedReader) Read(p []byte) (int, error) { return n, err } -func findMachoCodeSignature(r interface{}) (*macho.File, codesign.CodeSigCmd, bool) { +func findMachoCodeSignature(r any) (*macho.File, codesign.CodeSigCmd, bool) { ra, ok := r.(io.ReaderAt) if !ok { return nil, codesign.CodeSigCmd{}, false diff --git a/src/cmd/internal/test2json/test2json_test.go b/src/cmd/internal/test2json/test2json_test.go index 4683907888cdb..e69739d3fecde 100644 --- a/src/cmd/internal/test2json/test2json_test.go +++ b/src/cmd/internal/test2json/test2json_test.go @@ -145,7 +145,7 @@ func writeAndKill(w io.Writer, b []byte) { // and fails the test with a useful message if they don't match. func diffJSON(t *testing.T, have, want []byte) { t.Helper() - type event map[string]interface{} + type event map[string]any // Parse into events, one per line. parseEvents := func(b []byte) ([]event, []string) { diff --git a/src/cmd/internal/traceviewer/format.go b/src/cmd/internal/traceviewer/format.go index 871477447f159..3636c1053de04 100644 --- a/src/cmd/internal/traceviewer/format.go +++ b/src/cmd/internal/traceviewer/format.go @@ -16,20 +16,20 @@ type Data struct { } type Event struct { - Name string `json:"name,omitempty"` - Phase string `json:"ph"` - Scope string `json:"s,omitempty"` - Time float64 `json:"ts"` - Dur float64 `json:"dur,omitempty"` - PID uint64 `json:"pid"` - TID uint64 `json:"tid"` - ID uint64 `json:"id,omitempty"` - BindPoint string `json:"bp,omitempty"` - Stack int `json:"sf,omitempty"` - EndStack int `json:"esf,omitempty"` - Arg interface{} `json:"args,omitempty"` - Cname string `json:"cname,omitempty"` - Category string `json:"cat,omitempty"` + Name string `json:"name,omitempty"` + Phase string `json:"ph"` + Scope string `json:"s,omitempty"` + Time float64 `json:"ts"` + Dur float64 `json:"dur,omitempty"` + PID uint64 `json:"pid"` + TID uint64 `json:"tid"` + ID uint64 `json:"id,omitempty"` + BindPoint string `json:"bp,omitempty"` + Stack int `json:"sf,omitempty"` + EndStack int `json:"esf,omitempty"` + Arg any `json:"args,omitempty"` + Cname string `json:"cname,omitempty"` + Category string `json:"cat,omitempty"` } type Frame struct { diff --git a/src/cmd/nm/nm.go b/src/cmd/nm/nm.go index 457239921bc34..178eeb27bea34 100644 --- a/src/cmd/nm/nm.go +++ b/src/cmd/nm/nm.go @@ -93,7 +93,7 @@ func main() { var exitCode = 0 -func errorf(format string, args ...interface{}) { +func errorf(format string, args ...any) { log.Printf(format, args...) exitCode = 1 } diff --git a/src/cmd/pack/pack_test.go b/src/cmd/pack/pack_test.go index 7842b562dc3c1..81e78f53e28d0 100644 --- a/src/cmd/pack/pack_test.go +++ b/src/cmd/pack/pack_test.go @@ -203,7 +203,7 @@ func TestLargeDefs(t *testing.T) { } b := bufio.NewWriter(f) - printf := func(format string, args ...interface{}) { + printf := func(format string, args ...any) { _, err := fmt.Fprintf(b, format, args...) if err != nil { t.Fatalf("Writing to %s: %v", large, err) @@ -454,7 +454,7 @@ func (f *FakeFile) IsDir() bool { return false } -func (f *FakeFile) Sys() interface{} { +func (f *FakeFile) Sys() any { return nil } diff --git a/src/cmd/pprof/readlineui.go b/src/cmd/pprof/readlineui.go index 7ad712cd60b2c..b269177650ae5 100644 --- a/src/cmd/pprof/readlineui.go +++ b/src/cmd/pprof/readlineui.go @@ -69,18 +69,18 @@ func (r *readlineUI) ReadLine(prompt string) (string, error) { // It formats the text as fmt.Print would and adds a final \n if not already present. // For line-based UI, Print writes to standard error. // (Standard output is reserved for report data.) -func (r *readlineUI) Print(args ...interface{}) { +func (r *readlineUI) Print(args ...any) { r.print(false, args...) } // PrintErr shows an error message to the user. // It formats the text as fmt.Print would and adds a final \n if not already present. // For line-based UI, PrintErr writes to standard error. -func (r *readlineUI) PrintErr(args ...interface{}) { +func (r *readlineUI) PrintErr(args ...any) { r.print(true, args...) } -func (r *readlineUI) print(withColor bool, args ...interface{}) { +func (r *readlineUI) print(withColor bool, args ...any) { text := fmt.Sprint(args...) if !strings.HasSuffix(text, "\n") { text += "\n" diff --git a/src/cmd/trace/main.go b/src/cmd/trace/main.go index 3aeba223ee66d..a30db9a012ad1 100644 --- a/src/cmd/trace/main.go +++ b/src/cmd/trace/main.go @@ -206,7 +206,7 @@ var templMain = template.Must(template.New("").Parse(` `)) -func dief(msg string, args ...interface{}) { +func dief(msg string, args ...any) { fmt.Fprintf(os.Stderr, msg, args...) os.Exit(1) } diff --git a/src/cmd/trace/mmu.go b/src/cmd/trace/mmu.go index 1d1fd2ea94737..b71dcd6411041 100644 --- a/src/cmd/trace/mmu.go +++ b/src/cmd/trace/mmu.go @@ -155,7 +155,7 @@ func httpMMUPlot(w http.ResponseWriter, r *http.Request) { } // Create JSON response. - err = json.NewEncoder(w).Encode(map[string]interface{}{"xMin": int64(xMin), "xMax": int64(xMax), "quantiles": quantiles, "curve": plot}) + err = json.NewEncoder(w).Encode(map[string]any{"xMin": int64(xMin), "xMax": int64(xMax), "quantiles": quantiles, "curve": plot}) if err != nil { log.Printf("failed to serialize response: %v", err) return diff --git a/src/cmd/trace/trace.go b/src/cmd/trace/trace.go index ca10736c32030..0139639dae5c1 100644 --- a/src/cmd/trace/trace.go +++ b/src/cmd/trace/trace.go @@ -1054,7 +1054,7 @@ func (ctx *traceContext) emitInstant(ev *trace.Event, name, category string) { cname = colorLightGrey } } - var arg interface{} + var arg any if ev.Type == trace.EvProcStart { type Arg struct { ThreadID uint64 diff --git a/src/container/heap/example_intheap_test.go b/src/container/heap/example_intheap_test.go index 02d3d8668ee01..7e7ef8b8df711 100644 --- a/src/container/heap/example_intheap_test.go +++ b/src/container/heap/example_intheap_test.go @@ -17,13 +17,13 @@ func (h IntHeap) Len() int { return len(h) } func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *IntHeap) Push(x interface{}) { +func (h *IntHeap) Push(x any) { // Push and Pop use pointer receivers because they modify the slice's length, // not just its contents. *h = append(*h, x.(int)) } -func (h *IntHeap) Pop() interface{} { +func (h *IntHeap) Pop() any { old := *h n := len(old) x := old[n-1] diff --git a/src/container/heap/example_pq_test.go b/src/container/heap/example_pq_test.go index da1a233b70757..4511b6c33e0ff 100644 --- a/src/container/heap/example_pq_test.go +++ b/src/container/heap/example_pq_test.go @@ -34,14 +34,14 @@ func (pq PriorityQueue) Swap(i, j int) { pq[j].index = j } -func (pq *PriorityQueue) Push(x interface{}) { +func (pq *PriorityQueue) Push(x any) { n := len(*pq) item := x.(*Item) item.index = n *pq = append(*pq, item) } -func (pq *PriorityQueue) Pop() interface{} { +func (pq *PriorityQueue) Pop() any { old := *pq n := len(old) item := old[n-1] diff --git a/src/container/heap/heap.go b/src/container/heap/heap.go index 2e09da8613aa3..c3168f9b2779b 100644 --- a/src/container/heap/heap.go +++ b/src/container/heap/heap.go @@ -31,8 +31,8 @@ import "sort" // use heap.Push and heap.Pop. type Interface interface { sort.Interface - Push(x interface{}) // add x as element Len() - Pop() interface{} // remove and return element Len() - 1. + Push(x any) // add x as element Len() + Pop() any // remove and return element Len() - 1. } // Init establishes the heap invariants required by the other routines in this package. @@ -49,7 +49,7 @@ func Init(h Interface) { // Push pushes the element x onto the heap. // The complexity is O(log n) where n = h.Len(). -func Push(h Interface, x interface{}) { +func Push(h Interface, x any) { h.Push(x) up(h, h.Len()-1) } @@ -57,7 +57,7 @@ func Push(h Interface, x interface{}) { // Pop removes and returns the minimum element (according to Less) from the heap. // The complexity is O(log n) where n = h.Len(). // Pop is equivalent to Remove(h, 0). -func Pop(h Interface) interface{} { +func Pop(h Interface) any { n := h.Len() - 1 h.Swap(0, n) down(h, 0, n) @@ -66,7 +66,7 @@ func Pop(h Interface) interface{} { // Remove removes and returns the element at index i from the heap. // The complexity is O(log n) where n = h.Len(). -func Remove(h Interface, i int) interface{} { +func Remove(h Interface, i int) any { n := h.Len() - 1 if n != i { h.Swap(i, n) diff --git a/src/container/heap/heap_test.go b/src/container/heap/heap_test.go index f19f9cfa74b79..c9f9f140ea5ab 100644 --- a/src/container/heap/heap_test.go +++ b/src/container/heap/heap_test.go @@ -23,12 +23,12 @@ func (h *myHeap) Len() int { return len(*h) } -func (h *myHeap) Pop() (v interface{}) { +func (h *myHeap) Pop() (v any) { *h, v = (*h)[:h.Len()-1], (*h)[h.Len()-1] return } -func (h *myHeap) Push(v interface{}) { +func (h *myHeap) Push(v any) { *h = append(*h, v.(int)) } diff --git a/src/container/list/list.go b/src/container/list/list.go index aa89b7f599d9f..9555ad3900311 100644 --- a/src/container/list/list.go +++ b/src/container/list/list.go @@ -24,7 +24,7 @@ type Element struct { list *List // The value stored with this element. - Value interface{} + Value any } // Next returns the next list element or nil. @@ -100,7 +100,7 @@ func (l *List) insert(e, at *Element) *Element { } // insertValue is a convenience wrapper for insert(&Element{Value: v}, at). -func (l *List) insertValue(v interface{}, at *Element) *Element { +func (l *List) insertValue(v any, at *Element) *Element { return l.insert(&Element{Value: v}, at) } @@ -131,7 +131,7 @@ func (l *List) move(e, at *Element) { // Remove removes e from l if e is an element of list l. // It returns the element value e.Value. // The element must not be nil. -func (l *List) Remove(e *Element) interface{} { +func (l *List) Remove(e *Element) any { if e.list == l { // if e.list == l, l must have been initialized when e was inserted // in l or l == nil (e is a zero Element) and l.remove will crash @@ -141,13 +141,13 @@ func (l *List) Remove(e *Element) interface{} { } // PushFront inserts a new element e with value v at the front of list l and returns e. -func (l *List) PushFront(v interface{}) *Element { +func (l *List) PushFront(v any) *Element { l.lazyInit() return l.insertValue(v, &l.root) } // PushBack inserts a new element e with value v at the back of list l and returns e. -func (l *List) PushBack(v interface{}) *Element { +func (l *List) PushBack(v any) *Element { l.lazyInit() return l.insertValue(v, l.root.prev) } @@ -155,7 +155,7 @@ func (l *List) PushBack(v interface{}) *Element { // InsertBefore inserts a new element e with value v immediately before mark and returns e. // If mark is not an element of l, the list is not modified. // The mark must not be nil. -func (l *List) InsertBefore(v interface{}, mark *Element) *Element { +func (l *List) InsertBefore(v any, mark *Element) *Element { if mark.list != l { return nil } @@ -166,7 +166,7 @@ func (l *List) InsertBefore(v interface{}, mark *Element) *Element { // InsertAfter inserts a new element e with value v immediately after mark and returns e. // If mark is not an element of l, the list is not modified. // The mark must not be nil. -func (l *List) InsertAfter(v interface{}, mark *Element) *Element { +func (l *List) InsertAfter(v any, mark *Element) *Element { if mark.list != l { return nil } diff --git a/src/container/list/list_test.go b/src/container/list/list_test.go index c74724b3985a6..daa2114997051 100644 --- a/src/container/list/list_test.go +++ b/src/container/list/list_test.go @@ -141,7 +141,7 @@ func TestList(t *testing.T) { checkListPointers(t, l, []*Element{}) } -func checkList(t *testing.T, l *List, es []interface{}) { +func checkList(t *testing.T, l *List, es []any) { if !checkListLen(t, l, len(es)) { return } @@ -169,36 +169,36 @@ func TestExtending(t *testing.T) { l3 := New() l3.PushBackList(l1) - checkList(t, l3, []interface{}{1, 2, 3}) + checkList(t, l3, []any{1, 2, 3}) l3.PushBackList(l2) - checkList(t, l3, []interface{}{1, 2, 3, 4, 5}) + checkList(t, l3, []any{1, 2, 3, 4, 5}) l3 = New() l3.PushFrontList(l2) - checkList(t, l3, []interface{}{4, 5}) + checkList(t, l3, []any{4, 5}) l3.PushFrontList(l1) - checkList(t, l3, []interface{}{1, 2, 3, 4, 5}) + checkList(t, l3, []any{1, 2, 3, 4, 5}) - checkList(t, l1, []interface{}{1, 2, 3}) - checkList(t, l2, []interface{}{4, 5}) + checkList(t, l1, []any{1, 2, 3}) + checkList(t, l2, []any{4, 5}) l3 = New() l3.PushBackList(l1) - checkList(t, l3, []interface{}{1, 2, 3}) + checkList(t, l3, []any{1, 2, 3}) l3.PushBackList(l3) - checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3}) + checkList(t, l3, []any{1, 2, 3, 1, 2, 3}) l3 = New() l3.PushFrontList(l1) - checkList(t, l3, []interface{}{1, 2, 3}) + checkList(t, l3, []any{1, 2, 3}) l3.PushFrontList(l3) - checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3}) + checkList(t, l3, []any{1, 2, 3, 1, 2, 3}) l3 = New() l1.PushBackList(l3) - checkList(t, l1, []interface{}{1, 2, 3}) + checkList(t, l1, []any{1, 2, 3}) l1.PushFrontList(l3) - checkList(t, l1, []interface{}{1, 2, 3}) + checkList(t, l1, []any{1, 2, 3}) } func TestRemove(t *testing.T) { @@ -289,19 +289,19 @@ func TestMove(t *testing.T) { func TestZeroList(t *testing.T) { var l1 = new(List) l1.PushFront(1) - checkList(t, l1, []interface{}{1}) + checkList(t, l1, []any{1}) var l2 = new(List) l2.PushBack(1) - checkList(t, l2, []interface{}{1}) + checkList(t, l2, []any{1}) var l3 = new(List) l3.PushFrontList(l1) - checkList(t, l3, []interface{}{1}) + checkList(t, l3, []any{1}) var l4 = new(List) l4.PushBackList(l2) - checkList(t, l4, []interface{}{1}) + checkList(t, l4, []any{1}) } // Test that a list l is not modified when calling InsertBefore with a mark that is not an element of l. @@ -311,7 +311,7 @@ func TestInsertBeforeUnknownMark(t *testing.T) { l.PushBack(2) l.PushBack(3) l.InsertBefore(1, new(Element)) - checkList(t, &l, []interface{}{1, 2, 3}) + checkList(t, &l, []any{1, 2, 3}) } // Test that a list l is not modified when calling InsertAfter with a mark that is not an element of l. @@ -321,7 +321,7 @@ func TestInsertAfterUnknownMark(t *testing.T) { l.PushBack(2) l.PushBack(3) l.InsertAfter(1, new(Element)) - checkList(t, &l, []interface{}{1, 2, 3}) + checkList(t, &l, []any{1, 2, 3}) } // Test that a list l is not modified when calling MoveAfter or MoveBefore with a mark that is not an element of l. @@ -333,10 +333,10 @@ func TestMoveUnknownMark(t *testing.T) { e2 := l2.PushBack(2) l1.MoveAfter(e1, e2) - checkList(t, &l1, []interface{}{1}) - checkList(t, &l2, []interface{}{2}) + checkList(t, &l1, []any{1}) + checkList(t, &l2, []any{2}) l1.MoveBefore(e1, e2) - checkList(t, &l1, []interface{}{1}) - checkList(t, &l2, []interface{}{2}) + checkList(t, &l1, []any{1}) + checkList(t, &l2, []any{2}) } diff --git a/src/container/ring/example_test.go b/src/container/ring/example_test.go index 30bd0d74c9eee..4b659d25da0c7 100644 --- a/src/container/ring/example_test.go +++ b/src/container/ring/example_test.go @@ -88,7 +88,7 @@ func ExampleRing_Do() { } // Iterate through the ring and print its contents - r.Do(func(p interface{}) { + r.Do(func(p any) { fmt.Println(p.(int)) }) @@ -117,7 +117,7 @@ func ExampleRing_Move() { r = r.Move(3) // Iterate through the ring and print its contents - r.Do(func(p interface{}) { + r.Do(func(p any) { fmt.Println(p.(int)) }) @@ -154,7 +154,7 @@ func ExampleRing_Link() { rs := r.Link(s) // Iterate through the combined ring and print its contents - rs.Do(func(p interface{}) { + rs.Do(func(p any) { fmt.Println(p.(int)) }) @@ -182,7 +182,7 @@ func ExampleRing_Unlink() { r.Unlink(3) // Iterate through the remaining ring and print its contents - r.Do(func(p interface{}) { + r.Do(func(p any) { fmt.Println(p.(int)) }) diff --git a/src/container/ring/ring.go b/src/container/ring/ring.go index 6d3b3e5b32226..ce15032543be9 100644 --- a/src/container/ring/ring.go +++ b/src/container/ring/ring.go @@ -13,7 +13,7 @@ package ring // type Ring struct { next, prev *Ring - Value interface{} // for use by client; untouched by this library + Value any // for use by client; untouched by this library } func (r *Ring) init() *Ring { @@ -131,7 +131,7 @@ func (r *Ring) Len() int { // Do calls function f on each element of the ring, in forward order. // The behavior of Do is undefined if f changes *r. -func (r *Ring) Do(f func(interface{})) { +func (r *Ring) Do(f func(any)) { if r != nil { f(r.Value) for p := r.Next(); p != r; p = p.next { diff --git a/src/container/ring/ring_test.go b/src/container/ring/ring_test.go index 41d18abf8b6b1..28acbbc250f07 100644 --- a/src/container/ring/ring_test.go +++ b/src/container/ring/ring_test.go @@ -33,7 +33,7 @@ func verify(t *testing.T, r *Ring, N int, sum int) { // iteration n = 0 s := 0 - r.Do(func(p interface{}) { + r.Do(func(p any) { n++ if p != nil { s += p.(int) diff --git a/src/context/context.go b/src/context/context.go index a9e14703fd335..cf010b2a69547 100644 --- a/src/context/context.go +++ b/src/context/context.go @@ -150,7 +150,7 @@ type Context interface { // u, ok := ctx.Value(userKey).(*User) // return u, ok // } - Value(key interface{}) interface{} + Value(key any) any } // Canceled is the error returned by Context.Err when the context is canceled. @@ -182,7 +182,7 @@ func (*emptyCtx) Err() error { return nil } -func (*emptyCtx) Value(key interface{}) interface{} { +func (*emptyCtx) Value(key any) any { return nil } @@ -348,7 +348,7 @@ type cancelCtx struct { err error // set to non-nil by the first cancel call } -func (c *cancelCtx) Value(key interface{}) interface{} { +func (c *cancelCtx) Value(key any) any { if key == &cancelCtxKey { return c } @@ -520,7 +520,7 @@ func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { // interface{}, context keys often have concrete type // struct{}. Alternatively, exported context key variables' static // type should be a pointer or interface. -func WithValue(parent Context, key, val interface{}) Context { +func WithValue(parent Context, key, val any) Context { if parent == nil { panic("cannot create context from nil parent") } @@ -537,13 +537,13 @@ func WithValue(parent Context, key, val interface{}) Context { // delegates all other calls to the embedded Context. type valueCtx struct { Context - key, val interface{} + key, val any } // stringify tries a bit to stringify v, without using fmt, since we don't // want context depending on the unicode tables. This is only used by // *valueCtx.String(). -func stringify(v interface{}) string { +func stringify(v any) string { switch s := v.(type) { case stringer: return s.String() @@ -559,14 +559,14 @@ func (c *valueCtx) String() string { ", val " + stringify(c.val) + ")" } -func (c *valueCtx) Value(key interface{}) interface{} { +func (c *valueCtx) Value(key any) any { if c.key == key { return c.val } return value(c.Context, key) } -func value(c Context, key interface{}) interface{} { +func value(c Context, key any) any { for { switch ctx := c.(type) { case *valueCtx: diff --git a/src/context/context_test.go b/src/context/context_test.go index a2e2324a0eb25..8673c0fdeaa82 100644 --- a/src/context/context_test.go +++ b/src/context/context_test.go @@ -16,21 +16,21 @@ import ( type testingT interface { Deadline() (time.Time, bool) - Error(args ...interface{}) - Errorf(format string, args ...interface{}) + Error(args ...any) + Errorf(format string, args ...any) Fail() FailNow() Failed() bool - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) + Fatal(args ...any) + Fatalf(format string, args ...any) Helper() - Log(args ...interface{}) - Logf(format string, args ...interface{}) + Log(args ...any) + Logf(format string, args ...any) Name() string Parallel() - Skip(args ...interface{}) + Skip(args ...any) SkipNow() - Skipf(format string, args ...interface{}) + Skipf(format string, args ...any) Skipped() bool } @@ -553,7 +553,7 @@ func testLayers(t testingT, seed int64, testTimeout bool) { t.Parallel() r := rand.New(rand.NewSource(seed)) - errorf := func(format string, a ...interface{}) { + errorf := func(format string, a ...any) { t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) } const ( @@ -691,7 +691,7 @@ func XTestInvalidDerivedFail(t testingT) { } } -func recoveredValue(fn func()) (v interface{}) { +func recoveredValue(fn func()) (v any) { defer func() { v = recover() }() fn() return diff --git a/src/crypto/crypto.go b/src/crypto/crypto.go index cb87972afc761..fe1c0690bc221 100644 --- a/src/crypto/crypto.go +++ b/src/crypto/crypto.go @@ -159,7 +159,7 @@ func RegisterHash(h Hash, f func() hash.Hash) { // } // // which can be used for increased type safety within applications. -type PublicKey interface{} +type PublicKey any // PrivateKey represents a private key using an unspecified algorithm. // @@ -173,7 +173,7 @@ type PublicKey interface{} // // as well as purpose-specific interfaces such as Signer and Decrypter, which // can be used for increased type safety within applications. -type PrivateKey interface{} +type PrivateKey any // Signer is an interface for an opaque private key that can be used for // signing operations. For example, an RSA key kept in a hardware module. @@ -220,4 +220,4 @@ type Decrypter interface { Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error) } -type DecrypterOpts interface{} +type DecrypterOpts any diff --git a/src/crypto/ed25519/internal/edwards25519/scalar_alias_test.go b/src/crypto/ed25519/internal/edwards25519/scalar_alias_test.go index 18d800d556053..827153b9bd316 100644 --- a/src/crypto/ed25519/internal/edwards25519/scalar_alias_test.go +++ b/src/crypto/ed25519/internal/edwards25519/scalar_alias_test.go @@ -71,7 +71,7 @@ func TestScalarAliasing(t *testing.T) { return x == x1 && y == y1 } - for name, f := range map[string]interface{}{ + for name, f := range map[string]any{ "Negate": func(v, x Scalar) bool { return checkAliasingOneArg((*Scalar).Negate, v, x) }, diff --git a/src/crypto/tls/cipher_suites.go b/src/crypto/tls/cipher_suites.go index 4bf06468c6dae..d164991eec94c 100644 --- a/src/crypto/tls/cipher_suites.go +++ b/src/crypto/tls/cipher_suites.go @@ -140,7 +140,7 @@ type cipherSuite struct { ka func(version uint16) keyAgreement // flags is a bitmask of the suite* values, above. flags int - cipher func(key, iv []byte, isRead bool) interface{} + cipher func(key, iv []byte, isRead bool) any mac func(key []byte) hash.Hash aead func(key, fixedNonce []byte) aead } @@ -399,12 +399,12 @@ func aesgcmPreferred(ciphers []uint16) bool { return false } -func cipherRC4(key, iv []byte, isRead bool) interface{} { +func cipherRC4(key, iv []byte, isRead bool) any { cipher, _ := rc4.NewCipher(key) return cipher } -func cipher3DES(key, iv []byte, isRead bool) interface{} { +func cipher3DES(key, iv []byte, isRead bool) any { block, _ := des.NewTripleDESCipher(key) if isRead { return cipher.NewCBCDecrypter(block, iv) @@ -412,7 +412,7 @@ func cipher3DES(key, iv []byte, isRead bool) interface{} { return cipher.NewCBCEncrypter(block, iv) } -func cipherAES(key, iv []byte, isRead bool) interface{} { +func cipherAES(key, iv []byte, isRead bool) any { block, _ := aes.NewCipher(key) if isRead { return cipher.NewCBCDecrypter(block, iv) diff --git a/src/crypto/tls/common.go b/src/crypto/tls/common.go index bb5bec3c4d40f..e6e7598ce97ea 100644 --- a/src/crypto/tls/common.go +++ b/src/crypto/tls/common.go @@ -1466,7 +1466,7 @@ func defaultConfig() *Config { return &emptyConfig } -func unexpectedMessageError(wanted, got interface{}) error { +func unexpectedMessageError(wanted, got any) error { return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) } diff --git a/src/crypto/tls/conn.go b/src/crypto/tls/conn.go index 300e9a233c6c0..28ab063782000 100644 --- a/src/crypto/tls/conn.go +++ b/src/crypto/tls/conn.go @@ -163,16 +163,16 @@ func (c *Conn) NetConn() net.Conn { type halfConn struct { sync.Mutex - err error // first permanent error - version uint16 // protocol version - cipher interface{} // cipher algorithm + err error // first permanent error + version uint16 // protocol version + cipher any // cipher algorithm mac hash.Hash seq [8]byte // 64-bit sequence number scratchBuf [13]byte // to avoid allocs; interface method args escape - nextCipher interface{} // next encryption state - nextMac hash.Hash // next MAC algorithm + nextCipher any // next encryption state + nextMac hash.Hash // next MAC algorithm trafficSecret []byte // current TLS 1.3 traffic secret } @@ -197,7 +197,7 @@ func (hc *halfConn) setErrorLocked(err error) error { // prepareCipherSpec sets the encryption and MAC states // that a subsequent changeCipherSpec will use. -func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac hash.Hash) { +func (hc *halfConn) prepareCipherSpec(version uint16, cipher any, mac hash.Hash) { hc.version = version hc.nextCipher = cipher hc.nextMac = mac @@ -935,7 +935,7 @@ func (c *Conn) flush() (int, error) { // outBufPool pools the record-sized scratch buffers used by writeRecordLocked. var outBufPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new([]byte) }, } @@ -1011,7 +1011,7 @@ func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) { // readHandshake reads the next handshake message from // the record layer. -func (c *Conn) readHandshake() (interface{}, error) { +func (c *Conn) readHandshake() (any, error) { for c.hand.Len() < 4 { if err := c.readRecord(); err != nil { return nil, err diff --git a/src/crypto/tls/generate_cert.go b/src/crypto/tls/generate_cert.go index 58fdd025db7dc..74509c9deaab2 100644 --- a/src/crypto/tls/generate_cert.go +++ b/src/crypto/tls/generate_cert.go @@ -37,7 +37,7 @@ var ( ed25519Key = flag.Bool("ed25519", false, "Generate an Ed25519 key") ) -func publicKey(priv interface{}) interface{} { +func publicKey(priv any) any { switch k := priv.(type) { case *rsa.PrivateKey: return &k.PublicKey @@ -57,7 +57,7 @@ func main() { log.Fatalf("Missing required --host parameter") } - var priv interface{} + var priv any var err error switch *ecdsaCurve { case "": diff --git a/src/crypto/tls/handshake_client.go b/src/crypto/tls/handshake_client.go index 2ae6f3f534b6e..a3e00777f1255 100644 --- a/src/crypto/tls/handshake_client.go +++ b/src/crypto/tls/handshake_client.go @@ -657,7 +657,7 @@ func (hs *clientHandshakeState) establishKeys() error { clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) - var clientCipher, serverCipher interface{} + var clientCipher, serverCipher any var clientHash, serverHash hash.Hash if hs.suite.cipher != nil { clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) diff --git a/src/crypto/tls/handshake_client_test.go b/src/crypto/tls/handshake_client_test.go index 2158f3247b941..0950bb0ac4533 100644 --- a/src/crypto/tls/handshake_client_test.go +++ b/src/crypto/tls/handshake_client_test.go @@ -134,7 +134,7 @@ type clientTest struct { cert []byte // key, if not nil, contains either a *rsa.PrivateKey, ed25519.PrivateKey or // *ecdsa.PrivateKey which is the private key for the reference server. - key interface{} + key any // extensions, if not nil, contains a list of extension data to be returned // from the ServerHello. The data should be in standard TLS format with // a 2-byte uint16 type, 2-byte data length, followed by the extension data. @@ -171,7 +171,7 @@ func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, certPath := tempFile(string(cert)) defer os.Remove(certPath) - var key interface{} = testRSAPrivateKey + var key any = testRSAPrivateKey if test.key != nil { key = test.key } diff --git a/src/crypto/tls/handshake_messages_test.go b/src/crypto/tls/handshake_messages_test.go index bb8aea8670050..cc427bf72a017 100644 --- a/src/crypto/tls/handshake_messages_test.go +++ b/src/crypto/tls/handshake_messages_test.go @@ -14,7 +14,7 @@ import ( "time" ) -var tests = []interface{}{ +var tests = []any{ &clientHelloMsg{}, &serverHelloMsg{}, &finishedMsg{}, diff --git a/src/crypto/tls/handshake_server.go b/src/crypto/tls/handshake_server.go index 5cb152755bf3c..097046340b87b 100644 --- a/src/crypto/tls/handshake_server.go +++ b/src/crypto/tls/handshake_server.go @@ -681,7 +681,7 @@ func (hs *serverHandshakeState) establishKeys() error { clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) - var clientCipher, serverCipher interface{} + var clientCipher, serverCipher any var clientHash, serverHash hash.Hash if hs.suite.aead == nil { diff --git a/src/crypto/tls/handshake_server_test.go b/src/crypto/tls/handshake_server_test.go index 5fb2ebbbb3aa4..6d2c4056261fe 100644 --- a/src/crypto/tls/handshake_server_test.go +++ b/src/crypto/tls/handshake_server_test.go @@ -249,7 +249,7 @@ func TestTLS12OnlyCipherSuites(t *testing.T) { } c, s := localPipe(t) - replyChan := make(chan interface{}) + replyChan := make(chan any) go func() { cli := Client(c, testConfig) cli.vers = clientHello.vers @@ -304,7 +304,7 @@ func TestTLSPointFormats(t *testing.T) { } c, s := localPipe(t) - replyChan := make(chan interface{}) + replyChan := make(chan any) go func() { cli := Client(c, testConfig) cli.vers = clientHello.vers @@ -600,7 +600,7 @@ func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, return nil, nil, err } - connChan := make(chan interface{}, 1) + connChan := make(chan any, 1) go func() { tcpConn, err := l.Accept() if err != nil { diff --git a/src/crypto/x509/name_constraints_test.go b/src/crypto/x509/name_constraints_test.go index a6b5aa1ee6520..04c1e7a627453 100644 --- a/src/crypto/x509/name_constraints_test.go +++ b/src/crypto/x509/name_constraints_test.go @@ -1850,7 +1850,7 @@ func parseEKUs(ekuStrs []string) (ekus []ExtKeyUsage, unknowns []asn1.ObjectIden func TestConstraintCases(t *testing.T) { privateKeys := sync.Pool{ - New: func() interface{} { + New: func() any { priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { panic(err) diff --git a/src/crypto/x509/parser.go b/src/crypto/x509/parser.go index c2770f3f08dc0..5e6bd543686e5 100644 --- a/src/crypto/x509/parser.go +++ b/src/crypto/x509/parser.go @@ -229,7 +229,7 @@ func parseExtension(der cryptobyte.String) (pkix.Extension, error) { return ext, nil } -func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) { +func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (any, error) { der := cryptobyte.String(keyData.PublicKey.RightAlign()) switch algo { case RSA: diff --git a/src/crypto/x509/pkcs8.go b/src/crypto/x509/pkcs8.go index a5ee4cfbfeff1..d77efa315612a 100644 --- a/src/crypto/x509/pkcs8.go +++ b/src/crypto/x509/pkcs8.go @@ -30,7 +30,7 @@ type pkcs8 struct { // More types might be supported in the future. // // This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY". -func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) { +func ParsePKCS8PrivateKey(der []byte) (key any, err error) { var privKey pkcs8 if _, err := asn1.Unmarshal(der, &privKey); err != nil { if _, err := asn1.Unmarshal(der, &ecPrivateKey{}); err == nil { @@ -85,7 +85,7 @@ func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) { // and ed25519.PrivateKey. Unsupported key types result in an error. // // This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY". -func MarshalPKCS8PrivateKey(key interface{}) ([]byte, error) { +func MarshalPKCS8PrivateKey(key any) ([]byte, error) { var privKey pkcs8 switch k := key.(type) { diff --git a/src/crypto/x509/pkix/pkix.go b/src/crypto/x509/pkix/pkix.go index 62ae06549645f..e9179ed0679be 100644 --- a/src/crypto/x509/pkix/pkix.go +++ b/src/crypto/x509/pkix/pkix.go @@ -98,7 +98,7 @@ type RelativeDistinguishedNameSET []AttributeTypeAndValue // RFC 5280, Section 4.1.2.4. type AttributeTypeAndValue struct { Type asn1.ObjectIdentifier - Value interface{} + Value any } // AttributeTypeAndValueSET represents a set of ASN.1 sequences of diff --git a/src/crypto/x509/verify.go b/src/crypto/x509/verify.go index 1562ee57af1a9..e8c7707f3fee4 100644 --- a/src/crypto/x509/verify.go +++ b/src/crypto/x509/verify.go @@ -500,9 +500,9 @@ func (c *Certificate) checkNameConstraints(count *int, maxConstraintComparisons int, nameType string, name string, - parsedName interface{}, - match func(parsedName, constraint interface{}) (match bool, err error), - permitted, excluded interface{}) error { + parsedName any, + match func(parsedName, constraint any) (match bool, err error), + permitted, excluded any) error { excludedValue := reflect.ValueOf(excluded) @@ -609,7 +609,7 @@ func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *V } if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox, - func(parsedName, constraint interface{}) (bool, error) { + func(parsedName, constraint any) (bool, error) { return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string)) }, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil { return err @@ -622,7 +622,7 @@ func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *V } if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name, - func(parsedName, constraint interface{}) (bool, error) { + func(parsedName, constraint any) (bool, error) { return matchDomainConstraint(parsedName.(string), constraint.(string)) }, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil { return err @@ -636,7 +636,7 @@ func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *V } if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri, - func(parsedName, constraint interface{}) (bool, error) { + func(parsedName, constraint any) (bool, error) { return matchURIConstraint(parsedName.(*url.URL), constraint.(string)) }, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil { return err @@ -649,7 +649,7 @@ func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *V } if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip, - func(parsedName, constraint interface{}) (bool, error) { + func(parsedName, constraint any) (bool, error) { return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet)) }, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil { return err diff --git a/src/crypto/x509/x509.go b/src/crypto/x509/x509.go index b5c2b22cd746e..47be77d994df9 100644 --- a/src/crypto/x509/x509.go +++ b/src/crypto/x509/x509.go @@ -52,7 +52,7 @@ type pkixPublicKey struct { // ed25519.PublicKey. More types might be supported in the future. // // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY". -func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) { +func ParsePKIXPublicKey(derBytes []byte) (pub any, err error) { var pki publicKeyInfo if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil { if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil { @@ -69,7 +69,7 @@ func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) { return parsePublicKey(algo, &pki) } -func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) { +func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) { switch pub := pub.(type) { case *rsa.PublicKey: publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{ @@ -114,7 +114,7 @@ func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorith // and ed25519.PublicKey. Unsupported key types result in an error. // // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY". -func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { +func MarshalPKIXPublicKey(pub any) ([]byte, error) { var publicKeyBytes []byte var publicKeyAlgorithm pkix.AlgorithmIdentifier var err error @@ -636,7 +636,7 @@ type Certificate struct { SignatureAlgorithm SignatureAlgorithm PublicKeyAlgorithm PublicKeyAlgorithm - PublicKey interface{} + PublicKey any Version int SerialNumber *big.Int @@ -814,7 +814,7 @@ func (c *Certificate) getSANExtension() []byte { return nil } -func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error { +func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error { return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey) } @@ -1357,7 +1357,7 @@ func subjectBytes(cert *Certificate) ([]byte, error) { // signingParamsForPublicKey returns the parameters to use for signing with // priv. If requestedSigAlgo is not zero then it overrides the default // signature algorithm. -func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { +func signingParamsForPublicKey(pub any, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { var pubType PublicKeyAlgorithm switch pub := pub.(type) { @@ -1483,7 +1483,7 @@ var emptyASN1Subject = []byte{0x30, 0} // // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId // will be generated from the hash of the public key. -func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) ([]byte, error) { +func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) { key, ok := priv.(crypto.Signer) if !ok { return nil, errors.New("x509: certificate private key does not implement crypto.Signer") @@ -1648,7 +1648,7 @@ func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) { // // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL. // To generate a standards compliant CRL, use CreateRevocationList instead. -func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { +func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { key, ok := priv.(crypto.Signer) if !ok { return nil, errors.New("x509: certificate private key does not implement crypto.Signer") @@ -1723,7 +1723,7 @@ type CertificateRequest struct { SignatureAlgorithm SignatureAlgorithm PublicKeyAlgorithm PublicKeyAlgorithm - PublicKey interface{} + PublicKey any Subject pkix.Name @@ -1860,7 +1860,7 @@ func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) // ed25519.PrivateKey satisfies this.) // // The returned slice is the certificate request in DER encoding. -func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) { +func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) { key, ok := priv.(crypto.Signer) if !ok { return nil, errors.New("x509: certificate private key does not implement crypto.Signer") diff --git a/src/crypto/x509/x509_test.go b/src/crypto/x509/x509_test.go index 3345f5707520b..a42b852a42488 100644 --- a/src/crypto/x509/x509_test.go +++ b/src/crypto/x509/x509_test.go @@ -68,7 +68,7 @@ func TestPKCS1MismatchPublicKeyFormat(t *testing.T) { } } -func testParsePKIXPublicKey(t *testing.T, pemBytes string) (pub interface{}) { +func testParsePKIXPublicKey(t *testing.T, pemBytes string) (pub any) { block, _ := pem.Decode([]byte(pemBytes)) pub, err := ParsePKIXPublicKey(block.Bytes) if err != nil { @@ -581,7 +581,7 @@ func TestCreateSelfSignedCertificate(t *testing.T) { tests := []struct { name string - pub, priv interface{} + pub, priv any checkSig bool sigAlgo SignatureAlgorithm }{ @@ -1233,7 +1233,7 @@ func TestCRLCreation(t *testing.T) { tests := []struct { name string - priv interface{} + priv any cert *Certificate }{ {"RSA CA", privRSA, certRSA}, @@ -1385,7 +1385,7 @@ func TestCreateCertificateRequest(t *testing.T) { tests := []struct { name string - priv interface{} + priv any sigAlgo SignatureAlgorithm }{ {"RSA", testPrivateKey, SHA256WithRSA}, diff --git a/src/database/sql/convert.go b/src/database/sql/convert.go index c0997b7fc5d33..4d9d070137b01 100644 --- a/src/database/sql/convert.go +++ b/src/database/sql/convert.go @@ -104,7 +104,7 @@ func defaultCheckNamedValue(nv *driver.NamedValue) (err error) { // The statement ds may be nil, if no statement is available. // // ci must be locked. -func driverArgsConnLocked(ci driver.Conn, ds *driverStmt, args []interface{}) ([]driver.NamedValue, error) { +func driverArgsConnLocked(ci driver.Conn, ds *driverStmt, args []any) ([]driver.NamedValue, error) { nvargs := make([]driver.NamedValue, len(args)) // -1 means the driver doesn't know how to count the number of @@ -207,7 +207,7 @@ func driverArgsConnLocked(ci driver.Conn, ds *driverStmt, args []interface{}) ([ // convertAssign is the same as convertAssignRows, but without the optional // rows argument. -func convertAssign(dest, src interface{}) error { +func convertAssign(dest, src any) error { return convertAssignRows(dest, src, nil) } @@ -216,7 +216,7 @@ func convertAssign(dest, src interface{}) error { // dest should be a pointer type. If rows is passed in, the rows will // be used as the parent for any cursor values converted from a // driver.Rows to a *Rows. -func convertAssignRows(dest, src interface{}, rows *Rows) error { +func convertAssignRows(dest, src any, rows *Rows) error { // Common cases, without reflect. switch s := src.(type) { case string: @@ -248,7 +248,7 @@ func convertAssignRows(dest, src interface{}, rows *Rows) error { } *d = string(s) return nil - case *interface{}: + case *any: if d == nil { return errNilPtr } @@ -295,7 +295,7 @@ func convertAssignRows(dest, src interface{}, rows *Rows) error { } case nil: switch d := dest.(type) { - case *interface{}: + case *any: if d == nil { return errNilPtr } @@ -376,7 +376,7 @@ func convertAssignRows(dest, src interface{}, rows *Rows) error { *d = bv.(bool) } return err - case *interface{}: + case *any: *d = src return nil } @@ -495,7 +495,7 @@ func cloneBytes(b []byte) []byte { return c } -func asString(src interface{}) string { +func asString(src any) string { switch v := src.(type) { case string: return v diff --git a/src/database/sql/convert_test.go b/src/database/sql/convert_test.go index 400da7ea57723..6d09fa1eaee76 100644 --- a/src/database/sql/convert_test.go +++ b/src/database/sql/convert_test.go @@ -25,7 +25,7 @@ type ( ) type conversionTest struct { - s, d interface{} // source and destination + s, d any // source and destination // following are used if they're non-zero wantint int64 @@ -38,7 +38,7 @@ type conversionTest struct { wanttime time.Time wantbool bool // used if d is of type *bool wanterr string - wantiface interface{} + wantiface any wantptr *int64 // if non-nil, *d's pointed value must be equal to *wantptr wantnil bool // if true, *d must be *int64(nil) wantusrdef userDefined @@ -58,7 +58,7 @@ var ( scanf64 float64 scantime time.Time scanptr *int64 - scaniface interface{} + scaniface any ) func conversionTests() []conversionTest { @@ -161,7 +161,7 @@ func conversionTests() []conversionTest { {s: "1.5", d: &scanf64, wantf64: float64(1.5)}, // Pointers - {s: interface{}(nil), d: &scanptr, wantnil: true}, + {s: any(nil), d: &scanptr, wantnil: true}, {s: int64(42), d: &scanptr, wantptr: &answer}, // To interface{} @@ -185,27 +185,27 @@ func conversionTests() []conversionTest { } } -func intPtrValue(intptr interface{}) interface{} { +func intPtrValue(intptr any) any { return reflect.Indirect(reflect.Indirect(reflect.ValueOf(intptr))).Int() } -func intValue(intptr interface{}) int64 { +func intValue(intptr any) int64 { return reflect.Indirect(reflect.ValueOf(intptr)).Int() } -func uintValue(intptr interface{}) uint64 { +func uintValue(intptr any) uint64 { return reflect.Indirect(reflect.ValueOf(intptr)).Uint() } -func float64Value(ptr interface{}) float64 { +func float64Value(ptr any) float64 { return *(ptr.(*float64)) } -func float32Value(ptr interface{}) float32 { +func float32Value(ptr any) float32 { return *(ptr.(*float32)) } -func timeValue(ptr interface{}) time.Time { +func timeValue(ptr any) time.Time { return *(ptr.(*time.Time)) } @@ -216,7 +216,7 @@ func TestConversions(t *testing.T) { if err != nil { errstr = err.Error() } - errf := func(format string, args ...interface{}) { + errf := func(format string, args ...any) { base := fmt.Sprintf("convertAssign #%d: for %v (%T) -> %T, ", n, ct.s, ct.s, ct.d) t.Errorf(base+format, args...) } @@ -260,7 +260,7 @@ func TestConversions(t *testing.T) { errf("want pointer to %v, got %v", *ct.wantptr, intPtrValue(ct.d)) } } - if ifptr, ok := ct.d.(*interface{}); ok { + if ifptr, ok := ct.d.(*any); ok { if !reflect.DeepEqual(ct.wantiface, scaniface) { errf("want interface %#v, got %#v", ct.wantiface, scaniface) continue @@ -301,7 +301,7 @@ func TestNullString(t *testing.T) { type valueConverterTest struct { c driver.ValueConverter - in, out interface{} + in, out any err string } @@ -335,7 +335,7 @@ func TestValueConverters(t *testing.T) { func TestRawBytesAllocs(t *testing.T) { var tests = []struct { name string - in interface{} + in any want string }{ {"uint64", uint64(12345678), "12345678"}, @@ -355,7 +355,7 @@ func TestRawBytesAllocs(t *testing.T) { } buf := make(RawBytes, 10) - test := func(name string, in interface{}, want string) { + test := func(name string, in any, want string) { if err := convertAssign(&buf, in); err != nil { t.Fatalf("%s: convertAssign = %v", name, err) } @@ -430,11 +430,11 @@ func TestDriverArgs(t *testing.T) { var nilValuerPPtr *Valuer_P var nilStrPtr *string tests := []struct { - args []interface{} + args []any want []driver.NamedValue }{ 0: { - args: []interface{}{Valuer_V("foo")}, + args: []any{Valuer_V("foo")}, want: []driver.NamedValue{ { Ordinal: 1, @@ -443,7 +443,7 @@ func TestDriverArgs(t *testing.T) { }, }, 1: { - args: []interface{}{nilValuerVPtr}, + args: []any{nilValuerVPtr}, want: []driver.NamedValue{ { Ordinal: 1, @@ -452,7 +452,7 @@ func TestDriverArgs(t *testing.T) { }, }, 2: { - args: []interface{}{nilValuerPPtr}, + args: []any{nilValuerPPtr}, want: []driver.NamedValue{ { Ordinal: 1, @@ -461,7 +461,7 @@ func TestDriverArgs(t *testing.T) { }, }, 3: { - args: []interface{}{"plain-str"}, + args: []any{"plain-str"}, want: []driver.NamedValue{ { Ordinal: 1, @@ -470,7 +470,7 @@ func TestDriverArgs(t *testing.T) { }, }, 4: { - args: []interface{}{nilStrPtr}, + args: []any{nilStrPtr}, want: []driver.NamedValue{ { Ordinal: 1, diff --git a/src/database/sql/driver/driver.go b/src/database/sql/driver/driver.go index ea1de5a8fb6a8..5342315d124a9 100644 --- a/src/database/sql/driver/driver.go +++ b/src/database/sql/driver/driver.go @@ -58,7 +58,7 @@ import ( // in this package. This is used, for example, when a user selects a cursor // such as "select cursor(select * from my_table) from dual". If the Rows // from the select is closed, the cursor Rows will also be closed. -type Value interface{} +type Value any // NamedValue holds both the value name and value. type NamedValue struct { diff --git a/src/database/sql/driver/types.go b/src/database/sql/driver/types.go index 3337c2e0bc92a..506ce6c2cd3c3 100644 --- a/src/database/sql/driver/types.go +++ b/src/database/sql/driver/types.go @@ -29,7 +29,7 @@ import ( // to a user's type in a scan. type ValueConverter interface { // ConvertValue converts a value to a driver Value. - ConvertValue(v interface{}) (Value, error) + ConvertValue(v any) (Value, error) } // Valuer is the interface providing the Value method. @@ -60,7 +60,7 @@ var _ ValueConverter = boolType{} func (boolType) String() string { return "Bool" } -func (boolType) ConvertValue(src interface{}) (Value, error) { +func (boolType) ConvertValue(src any) (Value, error) { switch s := src.(type) { case bool: return s, nil @@ -105,7 +105,7 @@ type int32Type struct{} var _ ValueConverter = int32Type{} -func (int32Type) ConvertValue(v interface{}) (Value, error) { +func (int32Type) ConvertValue(v any) (Value, error) { rv := reflect.ValueOf(v) switch rv.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: @@ -138,7 +138,7 @@ var String stringType type stringType struct{} -func (stringType) ConvertValue(v interface{}) (Value, error) { +func (stringType) ConvertValue(v any) (Value, error) { switch v.(type) { case string, []byte: return v, nil @@ -152,7 +152,7 @@ type Null struct { Converter ValueConverter } -func (n Null) ConvertValue(v interface{}) (Value, error) { +func (n Null) ConvertValue(v any) (Value, error) { if v == nil { return nil, nil } @@ -165,7 +165,7 @@ type NotNull struct { Converter ValueConverter } -func (n NotNull) ConvertValue(v interface{}) (Value, error) { +func (n NotNull) ConvertValue(v any) (Value, error) { if v == nil { return nil, fmt.Errorf("nil value not allowed") } @@ -173,7 +173,7 @@ func (n NotNull) ConvertValue(v interface{}) (Value, error) { } // IsValue reports whether v is a valid Value parameter type. -func IsValue(v interface{}) bool { +func IsValue(v any) bool { if v == nil { return true } @@ -188,7 +188,7 @@ func IsValue(v interface{}) bool { // IsScanValue is equivalent to IsValue. // It exists for compatibility. -func IsScanValue(v interface{}) bool { +func IsScanValue(v any) bool { return IsValue(v) } @@ -233,7 +233,7 @@ func callValuerValue(vr Valuer) (v Value, err error) { return vr.Value() } -func (defaultConverter) ConvertValue(v interface{}) (Value, error) { +func (defaultConverter) ConvertValue(v any) (Value, error) { if IsValue(v) { return v, nil } diff --git a/src/database/sql/driver/types_test.go b/src/database/sql/driver/types_test.go index 4c2996da85f4e..80e5e05469186 100644 --- a/src/database/sql/driver/types_test.go +++ b/src/database/sql/driver/types_test.go @@ -12,8 +12,8 @@ import ( type valueConverterTest struct { c ValueConverter - in interface{} - out interface{} + in any + out any err string } diff --git a/src/database/sql/fakedb_test.go b/src/database/sql/fakedb_test.go index 34e97e012b1a3..8f953f6cb68dc 100644 --- a/src/database/sql/fakedb_test.go +++ b/src/database/sql/fakedb_test.go @@ -126,7 +126,7 @@ func (t *table) columnIndex(name string) int { } type row struct { - cols []interface{} // must be same size as its table colname + coltype + cols []any // must be same size as its table colname + coltype } type memToucher interface { @@ -198,10 +198,10 @@ type fakeStmt struct { closed bool - colName []string // used by CREATE, INSERT, SELECT (selected columns) - colType []string // used by CREATE - colValue []interface{} // used by INSERT (mix of strings and "?" for bound params) - placeholders int // used by INSERT/SELECT: number of ? params + colName []string // used by CREATE, INSERT, SELECT (selected columns) + colType []string // used by CREATE + colValue []any // used by INSERT (mix of strings and "?" for bound params) + placeholders int // used by INSERT/SELECT: number of ? params whereCol []boundCol // used by SELECT (all placeholders) @@ -504,7 +504,7 @@ func (c *fakeConn) QueryContext(ctx context.Context, query string, args []driver return nil, driver.ErrSkip } -func errf(msg string, args ...interface{}) error { +func errf(msg string, args ...any) error { return errors.New("fakedb: " + fmt.Sprintf(msg, args...)) } @@ -586,7 +586,7 @@ func (c *fakeConn) prepareInsert(ctx context.Context, stmt *fakeStmt, parts []st stmt.colName = append(stmt.colName, column) if !strings.HasPrefix(value, "?") { - var subsetVal interface{} + var subsetVal any // Convert to driver subset type switch ctype { case "string": @@ -829,9 +829,9 @@ func (s *fakeStmt) execInsert(args []driver.NamedValue, doInsert bool) (driver.R t.mu.Lock() defer t.mu.Unlock() - var cols []interface{} + var cols []any if doInsert { - cols = make([]interface{}, len(t.colname)) + cols = make([]any, len(t.colname)) } argPos := 0 for n, colname := range s.colName { @@ -839,7 +839,7 @@ func (s *fakeStmt) execInsert(args []driver.NamedValue, doInsert bool) (driver.R if colidx == -1 { return nil, fmt.Errorf("fakedb: column %q doesn't exist or dropped since prepared statement was created", colname) } - var val interface{} + var val any if strvalue, ok := s.colValue[n].(string); ok && strings.HasPrefix(strvalue, "?") { if strvalue == "?" { val = args[argPos].Value @@ -930,7 +930,7 @@ func (s *fakeStmt) QueryContext(ctx context.Context, args []driver.NamedValue) ( rows: [][]*row{ { { - cols: []interface{}{ + cols: []any{ txStatus, }, }, @@ -980,7 +980,7 @@ func (s *fakeStmt) QueryContext(ctx context.Context, args []driver.NamedValue) ( // lazy hack to avoid sprintf %v on a []byte tcol = string(bs) } - var argValue interface{} + var argValue any if wcol.Placeholder == "?" { argValue = args[wcol.Ordinal-1].Value } else { @@ -996,7 +996,7 @@ func (s *fakeStmt) QueryContext(ctx context.Context, args []driver.NamedValue) ( continue rows } } - mrow := &row{cols: make([]interface{}, len(s.colName))} + mrow := &row{cols: make([]any, len(s.colName))} for seli, name := range s.colName { mrow.cols[seli] = trow.cols[colIdx[name]] } @@ -1174,7 +1174,7 @@ func (rc *rowsCursor) NextResultSet() error { // type fakeDriverString struct{} -func (fakeDriverString) ConvertValue(v interface{}) (driver.Value, error) { +func (fakeDriverString) ConvertValue(v any) (driver.Value, error) { switch c := v.(type) { case string, []byte: return v, nil @@ -1189,7 +1189,7 @@ func (fakeDriverString) ConvertValue(v interface{}) (driver.Value, error) { type anyTypeConverter struct{} -func (anyTypeConverter) ConvertValue(v interface{}) (driver.Value, error) { +func (anyTypeConverter) ConvertValue(v any) (driver.Value, error) { return v, nil } @@ -1260,7 +1260,7 @@ func colTypeToReflectType(typ string) reflect.Type { case "datetime": return reflect.TypeOf(time.Time{}) case "any": - return reflect.TypeOf(new(interface{})).Elem() + return reflect.TypeOf(new(any)).Elem() } panic("invalid fakedb column type of " + typ) } diff --git a/src/database/sql/sql.go b/src/database/sql/sql.go index c5b4f50aa7440..d55cee1210971 100644 --- a/src/database/sql/sql.go +++ b/src/database/sql/sql.go @@ -92,7 +92,7 @@ type NamedArg struct { // Value is the value of the parameter. // It may be assigned the same value types as the query // arguments. - Value interface{} + Value any } // Named provides a more concise way to create NamedArg values. @@ -107,7 +107,7 @@ type NamedArg struct { // sql.Named("start", startTime), // sql.Named("end", endTime), // ) -func Named(name string, value interface{}) NamedArg { +func Named(name string, value any) NamedArg { // This method exists because the go1compat promise // doesn't guarantee that structs don't grow more fields, // so unkeyed struct literals are a vet error. Thus, we don't @@ -191,7 +191,7 @@ type NullString struct { } // Scan implements the Scanner interface. -func (ns *NullString) Scan(value interface{}) error { +func (ns *NullString) Scan(value any) error { if value == nil { ns.String, ns.Valid = "", false return nil @@ -217,7 +217,7 @@ type NullInt64 struct { } // Scan implements the Scanner interface. -func (n *NullInt64) Scan(value interface{}) error { +func (n *NullInt64) Scan(value any) error { if value == nil { n.Int64, n.Valid = 0, false return nil @@ -243,7 +243,7 @@ type NullInt32 struct { } // Scan implements the Scanner interface. -func (n *NullInt32) Scan(value interface{}) error { +func (n *NullInt32) Scan(value any) error { if value == nil { n.Int32, n.Valid = 0, false return nil @@ -269,7 +269,7 @@ type NullInt16 struct { } // Scan implements the Scanner interface. -func (n *NullInt16) Scan(value interface{}) error { +func (n *NullInt16) Scan(value any) error { if value == nil { n.Int16, n.Valid = 0, false return nil @@ -296,7 +296,7 @@ type NullByte struct { } // Scan implements the Scanner interface. -func (n *NullByte) Scan(value interface{}) error { +func (n *NullByte) Scan(value any) error { if value == nil { n.Byte, n.Valid = 0, false return nil @@ -323,7 +323,7 @@ type NullFloat64 struct { } // Scan implements the Scanner interface. -func (n *NullFloat64) Scan(value interface{}) error { +func (n *NullFloat64) Scan(value any) error { if value == nil { n.Float64, n.Valid = 0, false return nil @@ -349,7 +349,7 @@ type NullBool struct { } // Scan implements the Scanner interface. -func (n *NullBool) Scan(value interface{}) error { +func (n *NullBool) Scan(value any) error { if value == nil { n.Bool, n.Valid = false, false return nil @@ -375,7 +375,7 @@ type NullTime struct { } // Scan implements the Scanner interface. -func (n *NullTime) Scan(value interface{}) error { +func (n *NullTime) Scan(value any) error { if value == nil { n.Time, n.Valid = time.Time{}, false return nil @@ -412,7 +412,7 @@ type Scanner interface { // Reference types such as []byte are only valid until the next call to Scan // and should not be retained. Their underlying memory is owned by the driver. // If retention is necessary, copy their values before the next call to Scan. - Scan(src interface{}) error + Scan(src any) error } // Out may be used to retrieve OUTPUT value parameters from stored procedures. @@ -428,7 +428,7 @@ type Out struct { // Dest is a pointer to the value that will be set to the result of the // stored procedure's OUTPUT parameter. - Dest interface{} + Dest any // In is whether the parameter is an INOUT parameter. If so, the input value to the stored // procedure is the dereferenced value of Dest's pointer, which is then replaced with @@ -680,7 +680,7 @@ func (ds *driverStmt) Close() error { } // depSet is a finalCloser's outstanding dependencies -type depSet map[interface{}]bool // set of true bools +type depSet map[any]bool // set of true bools // The finalCloser interface is used by (*DB).addDep and related // dependency reference counting. @@ -692,13 +692,13 @@ type finalCloser interface { // addDep notes that x now depends on dep, and x's finalClose won't be // called until all of x's dependencies are removed with removeDep. -func (db *DB) addDep(x finalCloser, dep interface{}) { +func (db *DB) addDep(x finalCloser, dep any) { db.mu.Lock() defer db.mu.Unlock() db.addDepLocked(x, dep) } -func (db *DB) addDepLocked(x finalCloser, dep interface{}) { +func (db *DB) addDepLocked(x finalCloser, dep any) { if db.dep == nil { db.dep = make(map[finalCloser]depSet) } @@ -714,14 +714,14 @@ func (db *DB) addDepLocked(x finalCloser, dep interface{}) { // If x still has dependencies, nil is returned. // If x no longer has any dependencies, its finalClose method will be // called and its error value will be returned. -func (db *DB) removeDep(x finalCloser, dep interface{}) error { +func (db *DB) removeDep(x finalCloser, dep any) error { db.mu.Lock() fn := db.removeDepLocked(x, dep) db.mu.Unlock() return fn() } -func (db *DB) removeDepLocked(x finalCloser, dep interface{}) func() error { +func (db *DB) removeDepLocked(x finalCloser, dep any) func() error { xdep, ok := db.dep[x] if !ok { @@ -1627,7 +1627,7 @@ func (db *DB) prepareDC(ctx context.Context, dc *driverConn, release func(error) // ExecContext executes a query without returning any rows. // The args are for any placeholder parameters in the query. -func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) { +func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error) { var res Result var err error var isBadConn bool @@ -1649,11 +1649,11 @@ func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{} // // Exec uses context.Background internally; to specify the context, use // ExecContext. -func (db *DB) Exec(query string, args ...interface{}) (Result, error) { +func (db *DB) Exec(query string, args ...any) (Result, error) { return db.ExecContext(context.Background(), query, args...) } -func (db *DB) exec(ctx context.Context, query string, args []interface{}, strategy connReuseStrategy) (Result, error) { +func (db *DB) exec(ctx context.Context, query string, args []any, strategy connReuseStrategy) (Result, error) { dc, err := db.conn(ctx, strategy) if err != nil { return nil, err @@ -1661,7 +1661,7 @@ func (db *DB) exec(ctx context.Context, query string, args []interface{}, strate return db.execDC(ctx, dc, dc.releaseConn, query, args) } -func (db *DB) execDC(ctx context.Context, dc *driverConn, release func(error), query string, args []interface{}) (res Result, err error) { +func (db *DB) execDC(ctx context.Context, dc *driverConn, release func(error), query string, args []any) (res Result, err error) { defer func() { release(err) }() @@ -1702,7 +1702,7 @@ func (db *DB) execDC(ctx context.Context, dc *driverConn, release func(error), q // QueryContext executes a query that returns rows, typically a SELECT. // The args are for any placeholder parameters in the query. -func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { +func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) { var rows *Rows var err error var isBadConn bool @@ -1724,11 +1724,11 @@ func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{ // // Query uses context.Background internally; to specify the context, use // QueryContext. -func (db *DB) Query(query string, args ...interface{}) (*Rows, error) { +func (db *DB) Query(query string, args ...any) (*Rows, error) { return db.QueryContext(context.Background(), query, args...) } -func (db *DB) query(ctx context.Context, query string, args []interface{}, strategy connReuseStrategy) (*Rows, error) { +func (db *DB) query(ctx context.Context, query string, args []any, strategy connReuseStrategy) (*Rows, error) { dc, err := db.conn(ctx, strategy) if err != nil { return nil, err @@ -1741,7 +1741,7 @@ func (db *DB) query(ctx context.Context, query string, args []interface{}, strat // The connection gets released by the releaseConn function. // The ctx context is from a query method and the txctx context is from an // optional transaction context. -func (db *DB) queryDC(ctx, txctx context.Context, dc *driverConn, releaseConn func(error), query string, args []interface{}) (*Rows, error) { +func (db *DB) queryDC(ctx, txctx context.Context, dc *driverConn, releaseConn func(error), query string, args []any) (*Rows, error) { queryerCtx, ok := dc.ci.(driver.QueryerContext) var queryer driver.Queryer if !ok { @@ -1811,7 +1811,7 @@ func (db *DB) queryDC(ctx, txctx context.Context, dc *driverConn, releaseConn fu // If the query selects no rows, the *Row's Scan will return ErrNoRows. // Otherwise, the *Row's Scan scans the first selected row and discards // the rest. -func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row { +func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row { rows, err := db.QueryContext(ctx, query, args...) return &Row{rows: rows, err: err} } @@ -1825,7 +1825,7 @@ func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interfa // // QueryRow uses context.Background internally; to specify the context, use // QueryRowContext. -func (db *DB) QueryRow(query string, args ...interface{}) *Row { +func (db *DB) QueryRow(query string, args ...any) *Row { return db.QueryRowContext(context.Background(), query, args...) } @@ -1995,7 +1995,7 @@ func (c *Conn) PingContext(ctx context.Context) error { // ExecContext executes a query without returning any rows. // The args are for any placeholder parameters in the query. -func (c *Conn) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) { +func (c *Conn) ExecContext(ctx context.Context, query string, args ...any) (Result, error) { dc, release, err := c.grabConn(ctx) if err != nil { return nil, err @@ -2005,7 +2005,7 @@ func (c *Conn) ExecContext(ctx context.Context, query string, args ...interface{ // QueryContext executes a query that returns rows, typically a SELECT. // The args are for any placeholder parameters in the query. -func (c *Conn) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { +func (c *Conn) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) { dc, release, err := c.grabConn(ctx) if err != nil { return nil, err @@ -2019,7 +2019,7 @@ func (c *Conn) QueryContext(ctx context.Context, query string, args ...interface // If the query selects no rows, the *Row's Scan will return ErrNoRows. // Otherwise, the *Row's Scan scans the first selected row and discards // the rest. -func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row { +func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row { rows, err := c.QueryContext(ctx, query, args...) return &Row{rows: rows, err: err} } @@ -2045,7 +2045,7 @@ func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error) // // Once f returns and err is not driver.ErrBadConn, the Conn will continue to be usable // until Conn.Close is called. -func (c *Conn) Raw(f func(driverConn interface{}) error) (err error) { +func (c *Conn) Raw(f func(driverConn any) error) (err error) { var dc *driverConn var release releaseConn @@ -2483,7 +2483,7 @@ func (tx *Tx) Stmt(stmt *Stmt) *Stmt { // ExecContext executes a query that doesn't return rows. // For example: an INSERT and UPDATE. -func (tx *Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) { +func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (Result, error) { dc, release, err := tx.grabConn(ctx) if err != nil { return nil, err @@ -2496,12 +2496,12 @@ func (tx *Tx) ExecContext(ctx context.Context, query string, args ...interface{} // // Exec uses context.Background internally; to specify the context, use // ExecContext. -func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) { +func (tx *Tx) Exec(query string, args ...any) (Result, error) { return tx.ExecContext(context.Background(), query, args...) } // QueryContext executes a query that returns rows, typically a SELECT. -func (tx *Tx) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { +func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) { dc, release, err := tx.grabConn(ctx) if err != nil { return nil, err @@ -2514,7 +2514,7 @@ func (tx *Tx) QueryContext(ctx context.Context, query string, args ...interface{ // // Query uses context.Background internally; to specify the context, use // QueryContext. -func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) { +func (tx *Tx) Query(query string, args ...any) (*Rows, error) { return tx.QueryContext(context.Background(), query, args...) } @@ -2524,7 +2524,7 @@ func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) { // If the query selects no rows, the *Row's Scan will return ErrNoRows. // Otherwise, the *Row's Scan scans the first selected row and discards // the rest. -func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row { +func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row { rows, err := tx.QueryContext(ctx, query, args...) return &Row{rows: rows, err: err} } @@ -2538,7 +2538,7 @@ func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...interfa // // QueryRow uses context.Background internally; to specify the context, use // QueryRowContext. -func (tx *Tx) QueryRow(query string, args ...interface{}) *Row { +func (tx *Tx) QueryRow(query string, args ...any) *Row { return tx.QueryRowContext(context.Background(), query, args...) } @@ -2615,7 +2615,7 @@ type Stmt struct { // ExecContext executes a prepared statement with the given arguments and // returns a Result summarizing the effect of the statement. -func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (Result, error) { +func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error) { s.closemu.RLock() defer s.closemu.RUnlock() @@ -2647,11 +2647,11 @@ func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (Result, er // // Exec uses context.Background internally; to specify the context, use // ExecContext. -func (s *Stmt) Exec(args ...interface{}) (Result, error) { +func (s *Stmt) Exec(args ...any) (Result, error) { return s.ExecContext(context.Background(), args...) } -func resultFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...interface{}) (Result, error) { +func resultFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...any) (Result, error) { ds.Lock() defer ds.Unlock() @@ -2763,7 +2763,7 @@ func (s *Stmt) prepareOnConnLocked(ctx context.Context, dc *driverConn) (*driver // QueryContext executes a prepared query statement with the given arguments // and returns the query results as a *Rows. -func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*Rows, error) { +func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error) { s.closemu.RLock() defer s.closemu.RUnlock() @@ -2821,11 +2821,11 @@ func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*Rows, er // // Query uses context.Background internally; to specify the context, use // QueryContext. -func (s *Stmt) Query(args ...interface{}) (*Rows, error) { +func (s *Stmt) Query(args ...any) (*Rows, error) { return s.QueryContext(context.Background(), args...) } -func rowsiFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...interface{}) (driver.Rows, error) { +func rowsiFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...any) (driver.Rows, error) { ds.Lock() defer ds.Unlock() dargs, err := driverArgsConnLocked(ci, ds, args) @@ -2841,7 +2841,7 @@ func rowsiFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, arg // If the query selects no rows, the *Row's Scan will return ErrNoRows. // Otherwise, the *Row's Scan scans the first selected row and discards // the rest. -func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *Row { +func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row { rows, err := s.QueryContext(ctx, args...) if err != nil { return &Row{err: err} @@ -2863,7 +2863,7 @@ func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *Row { // // QueryRow uses context.Background internally; to specify the context, use // QueryRowContext. -func (s *Stmt) QueryRow(args ...interface{}) *Row { +func (s *Stmt) QueryRow(args ...any) *Row { return s.QueryRowContext(context.Background(), args...) } @@ -3185,7 +3185,7 @@ func rowsColumnInfoSetupConnLocked(rowsi driver.Rows) []*ColumnType { if prop, ok := rowsi.(driver.RowsColumnTypeScanType); ok { ci.scanType = prop.ColumnTypeScanType(i) } else { - ci.scanType = reflect.TypeOf(new(interface{})).Elem() + ci.scanType = reflect.TypeOf(new(any)).Elem() } if prop, ok := rowsi.(driver.RowsColumnTypeDatabaseTypeName); ok { ci.databaseType = prop.ColumnTypeDatabaseTypeName(i) @@ -3263,7 +3263,7 @@ func rowsColumnInfoSetupConnLocked(rowsi driver.Rows) []*ColumnType { // // If any of the first arguments implementing Scanner returns an error, // that error will be wrapped in the returned error -func (rs *Rows) Scan(dest ...interface{}) error { +func (rs *Rows) Scan(dest ...any) error { rs.closemu.RLock() if rs.lasterr != nil && rs.lasterr != io.EOF { @@ -3346,7 +3346,7 @@ type Row struct { // If more than one row matches the query, // Scan uses the first row and discards the rest. If no row matches // the query, Scan returns ErrNoRows. -func (r *Row) Scan(dest ...interface{}) error { +func (r *Row) Scan(dest ...any) error { if r.err != nil { return r.err } diff --git a/src/database/sql/sql_test.go b/src/database/sql/sql_test.go index b887b40d71360..1bb9afc4070e9 100644 --- a/src/database/sql/sql_test.go +++ b/src/database/sql/sql_test.go @@ -135,7 +135,7 @@ func TestDriverPanic(t *testing.T) { exec(t, db, "WIPE") // check not deadlocked } -func exec(t testing.TB, db *DB, query string, args ...interface{}) { +func exec(t testing.TB, db *DB, query string, args ...any) { t.Helper() _, err := db.Exec(query, args...) if err != nil { @@ -743,7 +743,7 @@ func TestRowsColumnTypes(t *testing.T) { } types[i] = st } - values := make([]interface{}, len(tt)) + values := make([]any, len(tt)) for i := range values { values[i] = reflect.New(types[i]).Interface() } @@ -1006,23 +1006,23 @@ func TestExec(t *testing.T) { defer stmt.Close() type execTest struct { - args []interface{} + args []any wantErr string } execTests := []execTest{ // Okay: - {[]interface{}{"Brad", 31}, ""}, - {[]interface{}{"Brad", int64(31)}, ""}, - {[]interface{}{"Bob", "32"}, ""}, - {[]interface{}{7, 9}, ""}, + {[]any{"Brad", 31}, ""}, + {[]any{"Brad", int64(31)}, ""}, + {[]any{"Bob", "32"}, ""}, + {[]any{7, 9}, ""}, // Invalid conversions: - {[]interface{}{"Brad", int64(0xFFFFFFFF)}, "sql: converting argument $2 type: sql/driver: value 4294967295 overflows int32"}, - {[]interface{}{"Brad", "strconv fail"}, `sql: converting argument $2 type: sql/driver: value "strconv fail" can't be converted to int32`}, + {[]any{"Brad", int64(0xFFFFFFFF)}, "sql: converting argument $2 type: sql/driver: value 4294967295 overflows int32"}, + {[]any{"Brad", "strconv fail"}, `sql: converting argument $2 type: sql/driver: value "strconv fail" can't be converted to int32`}, // Wrong number of args: - {[]interface{}{}, "sql: expected 2 arguments, got 0"}, - {[]interface{}{1, 2, 3}, "sql: expected 2 arguments, got 3"}, + {[]any{}, "sql: expected 2 arguments, got 0"}, + {[]any{1, 2, 3}, "sql: expected 2 arguments, got 3"}, } for n, et := range execTests { _, err := stmt.Exec(et.args...) @@ -1409,7 +1409,7 @@ func TestConnRaw(t *testing.T) { defer conn.Close() sawFunc := false - err = conn.Raw(func(dc interface{}) error { + err = conn.Raw(func(dc any) error { sawFunc = true if _, ok := dc.(*fakeConn); !ok { return fmt.Errorf("got %T want *fakeConn", dc) @@ -1436,7 +1436,7 @@ func TestConnRaw(t *testing.T) { t.Fatal("expected connection to be closed after panic") } }() - err = conn.Raw(func(dc interface{}) error { + err = conn.Raw(func(dc any) error { panic("Conn.Raw panic should return an error") }) t.Fatal("expected panic from Raw func") @@ -1495,7 +1495,7 @@ func TestInvalidNilValues(t *testing.T) { tests := []struct { name string - input interface{} + input any expectedError string }{ { @@ -1593,7 +1593,7 @@ func TestConnIsValid(t *testing.T) { t.Fatal(err) } - err = c.Raw(func(raw interface{}) error { + err = c.Raw(func(raw any) error { dc := raw.(*fakeConn) dc.stickyBad = true return nil @@ -1772,9 +1772,9 @@ func TestIssue6651(t *testing.T) { } type nullTestRow struct { - nullParam interface{} - notNullParam interface{} - scanNullVal interface{} + nullParam any + notNullParam any + scanNullVal any } type nullTestSpec struct { @@ -4129,7 +4129,7 @@ func TestNamedValueChecker(t *testing.T) { t.Fatal("select", err) } - list := []struct{ got, want interface{} }{ + list := []struct{ got, want any }{ {o1, "from-server"}, {dec1, decimalInt{123}}, {str1, "hello"}, @@ -4318,7 +4318,7 @@ type alwaysErrScanner struct{} var errTestScanWrap = errors.New("errTestScanWrap") -func (alwaysErrScanner) Scan(interface{}) error { +func (alwaysErrScanner) Scan(any) error { return errTestScanWrap } diff --git a/src/debug/dwarf/entry.go b/src/debug/dwarf/entry.go index 25a3b5beec309..cbdc838a12b1d 100644 --- a/src/debug/dwarf/entry.go +++ b/src/debug/dwarf/entry.go @@ -261,7 +261,7 @@ type Entry struct { // ClassUnknown. type Field struct { Attr Attr - Val interface{} + Val any Class Class } @@ -382,7 +382,7 @@ func (i Class) GoString() string { // the check that the value has the expected dynamic type, as in: // v, ok := e.Val(AttrSibling).(int64) // -func (e *Entry) Val(a Attr) interface{} { +func (e *Entry) Val(a Attr) any { if f := e.AttrField(a); f != nil { return f.Val } @@ -501,7 +501,7 @@ func (b *buf) entry(cu *Entry, atab abbrevTable, ubase Offset, vers int) *Entry fmt = format(b.uint()) e.Field[i].Class = formToClass(fmt, a.field[i].attr, vers, b) } - var val interface{} + var val any switch fmt { default: b.error("unknown entry attr format 0x" + strconv.FormatInt(int64(fmt), 16)) diff --git a/src/debug/dwarf/entry_test.go b/src/debug/dwarf/entry_test.go index 1f41d742ea5de..8c6ca7259ea60 100644 --- a/src/debug/dwarf/entry_test.go +++ b/src/debug/dwarf/entry_test.go @@ -277,7 +277,7 @@ func TestUnitIteration(t *testing.T) { for _, file := range files { t.Run(file, func(t *testing.T) { d := elfData(t, file) - var units [2][]interface{} + var units [2][]any for method := range units { for r := d.Reader(); ; { ent, err := r.Next() diff --git a/src/debug/elf/elf_test.go b/src/debug/elf/elf_test.go index f8985a8992361..a61b491090d17 100644 --- a/src/debug/elf/elf_test.go +++ b/src/debug/elf/elf_test.go @@ -10,7 +10,7 @@ import ( ) type nameTest struct { - val interface{} + val any str string } diff --git a/src/debug/elf/file.go b/src/debug/elf/file.go index e265796ddc3be..eefcaab8d6994 100644 --- a/src/debug/elf/file.go +++ b/src/debug/elf/file.go @@ -185,7 +185,7 @@ type Symbol struct { type FormatError struct { off int64 msg string - val interface{} + val any } func (e *FormatError) Error() string { diff --git a/src/debug/gosym/symtab.go b/src/debug/gosym/symtab.go index 72490dca8affe..4e63f1cdf705e 100644 --- a/src/debug/gosym/symtab.go +++ b/src/debug/gosym/symtab.go @@ -751,7 +751,7 @@ func (e *UnknownLineError) Error() string { type DecodingError struct { off int msg string - val interface{} + val any } func (e *DecodingError) Error() string { diff --git a/src/debug/macho/file.go b/src/debug/macho/file.go index cdc500e47623e..b57dba8496bf6 100644 --- a/src/debug/macho/file.go +++ b/src/debug/macho/file.go @@ -184,7 +184,7 @@ type Symbol struct { type FormatError struct { off int64 msg string - val interface{} + val any } func (e *FormatError) Error() string { diff --git a/src/debug/macho/file_test.go b/src/debug/macho/file_test.go index 9beeb80dd27c1..313c376c54a27 100644 --- a/src/debug/macho/file_test.go +++ b/src/debug/macho/file_test.go @@ -15,7 +15,7 @@ import ( type fileTest struct { file string hdr FileHeader - loads []interface{} + loads []any sections []*SectionHeader relocations map[string][]Reloc } @@ -24,7 +24,7 @@ var fileTests = []fileTest{ { "testdata/gcc-386-darwin-exec.base64", FileHeader{0xfeedface, Cpu386, 0x3, 0x2, 0xc, 0x3c0, 0x85}, - []interface{}{ + []any{ &SegmentHeader{LoadCmdSegment, 0x38, "__PAGEZERO", 0x0, 0x1000, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, &SegmentHeader{LoadCmdSegment, 0xc0, "__TEXT", 0x1000, 0x1000, 0x0, 0x1000, 0x7, 0x5, 0x2, 0x0}, &SegmentHeader{LoadCmdSegment, 0xc0, "__DATA", 0x2000, 0x1000, 0x1000, 0x1000, 0x7, 0x3, 0x2, 0x0}, @@ -50,7 +50,7 @@ var fileTests = []fileTest{ { "testdata/gcc-amd64-darwin-exec.base64", FileHeader{0xfeedfacf, CpuAmd64, 0x80000003, 0x2, 0xb, 0x568, 0x85}, - []interface{}{ + []any{ &SegmentHeader{LoadCmdSegment64, 0x48, "__PAGEZERO", 0x0, 0x100000000, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, &SegmentHeader{LoadCmdSegment64, 0x1d8, "__TEXT", 0x100000000, 0x1000, 0x0, 0x1000, 0x7, 0x5, 0x5, 0x0}, &SegmentHeader{LoadCmdSegment64, 0x138, "__DATA", 0x100001000, 0x1000, 0x1000, 0x1000, 0x7, 0x3, 0x3, 0x0}, @@ -78,7 +78,7 @@ var fileTests = []fileTest{ { "testdata/gcc-amd64-darwin-exec-debug.base64", FileHeader{0xfeedfacf, CpuAmd64, 0x80000003, 0xa, 0x4, 0x5a0, 0}, - []interface{}{ + []any{ nil, // LC_UUID &SegmentHeader{LoadCmdSegment64, 0x1d8, "__TEXT", 0x100000000, 0x1000, 0x0, 0x0, 0x7, 0x5, 0x5, 0x0}, &SegmentHeader{LoadCmdSegment64, 0x138, "__DATA", 0x100001000, 0x1000, 0x0, 0x0, 0x7, 0x3, 0x3, 0x0}, @@ -106,7 +106,7 @@ var fileTests = []fileTest{ { "testdata/clang-386-darwin-exec-with-rpath.base64", FileHeader{0xfeedface, Cpu386, 0x3, 0x2, 0x10, 0x42c, 0x1200085}, - []interface{}{ + []any{ nil, // LC_SEGMENT nil, // LC_SEGMENT nil, // LC_SEGMENT @@ -130,7 +130,7 @@ var fileTests = []fileTest{ { "testdata/clang-amd64-darwin-exec-with-rpath.base64", FileHeader{0xfeedfacf, CpuAmd64, 0x80000003, 0x2, 0x10, 0x4c8, 0x200085}, - []interface{}{ + []any{ nil, // LC_SEGMENT nil, // LC_SEGMENT nil, // LC_SEGMENT diff --git a/src/debug/pe/file.go b/src/debug/pe/file.go index ab00a48f5cfb7..aa0955a1334e8 100644 --- a/src/debug/pe/file.go +++ b/src/debug/pe/file.go @@ -22,7 +22,7 @@ const seekStart = 0 // A File represents an open PE file. type File struct { FileHeader - OptionalHeader interface{} // of type *OptionalHeader32 or *OptionalHeader64 + OptionalHeader any // of type *OptionalHeader32 or *OptionalHeader64 Sections []*Section Symbols []*Symbol // COFF symbols with auxiliary symbol records removed COFFSymbols []COFFSymbol // all COFF symbols (including auxiliary symbol records) @@ -452,7 +452,7 @@ func (e *FormatError) Error() string { // and its size as seen in the file header. // It parses the given size of bytes and returns optional header. It infers whether the // bytes being parsed refer to 32 bit or 64 bit version of optional header. -func readOptionalHeader(r io.ReadSeeker, sz uint16) (interface{}, error) { +func readOptionalHeader(r io.ReadSeeker, sz uint16) (any, error) { // If optional header size is 0, return empty optional header. if sz == 0 { return nil, nil @@ -473,7 +473,7 @@ func readOptionalHeader(r io.ReadSeeker, sz uint16) (interface{}, error) { // read reads from io.ReadSeeke, r, into data. var err error - read := func(data interface{}) bool { + read := func(data any) bool { err = binary.Read(r, binary.LittleEndian, data) return err == nil } diff --git a/src/debug/pe/file_test.go b/src/debug/pe/file_test.go index 8964b4f847be6..5368e08ad7234 100644 --- a/src/debug/pe/file_test.go +++ b/src/debug/pe/file_test.go @@ -22,7 +22,7 @@ import ( type fileTest struct { file string hdr FileHeader - opthdr interface{} + opthdr any sections []*SectionHeader symbols []*Symbol hasNoDwarfInfo bool @@ -250,7 +250,7 @@ var fileTests = []fileTest{ }, } -func isOptHdrEq(a, b interface{}) bool { +func isOptHdrEq(a, b any) bool { switch va := a.(type) { case *OptionalHeader32: vb, ok := b.(*OptionalHeader32) diff --git a/src/debug/plan9obj/file.go b/src/debug/plan9obj/file.go index c054635148d10..0c33fa10bb779 100644 --- a/src/debug/plan9obj/file.go +++ b/src/debug/plan9obj/file.go @@ -82,7 +82,7 @@ type Sym struct { type formatError struct { off int msg string - val interface{} + val any } func (e *formatError) Error() string { diff --git a/src/embed/embed.go b/src/embed/embed.go index 24c3a89e9bd72..9737ccdf6bb49 100644 --- a/src/embed/embed.go +++ b/src/embed/embed.go @@ -232,7 +232,7 @@ func (f *file) Name() string { _, elem, _ := split(f.name); return func (f *file) Size() int64 { return int64(len(f.data)) } func (f *file) ModTime() time.Time { return time.Time{} } func (f *file) IsDir() bool { _, _, isDir := split(f.name); return isDir } -func (f *file) Sys() interface{} { return nil } +func (f *file) Sys() any { return nil } func (f *file) Type() fs.FileMode { return f.Mode().Type() } func (f *file) Info() (fs.FileInfo, error) { return f, nil } diff --git a/src/embed/internal/embedtest/embed_test.go b/src/embed/internal/embedtest/embed_test.go index 1337e421bda86..cbd58ee846aa2 100644 --- a/src/embed/internal/embedtest/embed_test.go +++ b/src/embed/internal/embedtest/embed_test.go @@ -162,7 +162,7 @@ func TestAliases(t *testing.T) { if e != nil { t.Fatal("ReadFile:", e) } - check := func(g interface{}) { + check := func(g any) { got := reflect.ValueOf(g) for i := 0; i < got.Len(); i++ { if byte(got.Index(i).Uint()) != want[i] { diff --git a/src/encoding/ascii85/ascii85_test.go b/src/encoding/ascii85/ascii85_test.go index c637103942643..9e6b34e9972b4 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 d0e1c6b176976..cad1d7b08f8e9 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 8985538468e6b..b1e05b96ae395 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 5b4d786d49557..c243349175623 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 f0217ba8a5e25..d9c3cf48fa21c 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 8fb22b907810e..dbd2b613b42ae 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 51047402bd48b..57256a3846acb 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 52417a7933473..ee933461ee1a1 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 83af89e8a7c88..9e1b5f12db404 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 b994b897ce1b5..4c10daaf68800 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 f38e88b638abb..1ca9d878eecfc 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 5ceb2bfac7b4b..b6d5a3e95c452 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 96e215eb8c16d..86f54b41932b7 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 e49b452f6c372..548d614f52474 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 32865a7edee49..5a80e6c3e827e 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 a358d5bc3009d..6934841b3af8c 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 949333bc03701..3c9515b5ed6df 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 6d2c8db42d0d8..1d5dde22a4eeb 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 516aeea92c606..bdee39c447d5d 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 412a348137f80..6e2c7242324fa 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 fa3e802d4e1f0..f5f8db8bcb4a3 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 73c7b09fb6f6f..95609140b0d58 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 df4c5e1a1693a..555df0b7e876a 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 96bf9fb5ffded..c2c036b60914d 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 4f40197797e34..1f5e3e446a9c9 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 0dad951095270..0b021f0074991 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 fbecf1b59397b..2261c770c01f2 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 f00898a798d31..b8f4ff2c1d602 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 9dc1903e2db24..dbaa821becc10 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 3737516a45065..3474b3e4810de 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 81f404f4267d0..6362170d5df22 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 c284f2d9650e3..0e156d98e9454 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 bbb4e6a28d24f..6330efd3c21f9 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 1f0eb7634115e..6859be04a221e 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 cb95905f5b83a..5fdbae7ef0a8b 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 48b0ec055c17f..0701e18625953 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 8c2e70fa22ee6..391fe731a800f 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 33d0b417b91e1..8a0a9c253ade3 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 { diff --git a/src/errors/wrap.go b/src/errors/wrap.go index ab3cdb86d31f5..263ae16b48dc0 100644 --- a/src/errors/wrap.go +++ b/src/errors/wrap.go @@ -75,7 +75,7 @@ func Is(err, target error) bool { // // As panics if target is not a non-nil pointer to either a type that implements // error, or to any interface type. -func As(err error, target interface{}) bool { +func As(err error, target any) bool { if target == nil { panic("errors: target cannot be nil") } @@ -93,7 +93,7 @@ func As(err error, target interface{}) bool { val.Elem().Set(reflectlite.ValueOf(err)) return true } - if x, ok := err.(interface{ As(interface{}) bool }); ok && x.As(target) { + if x, ok := err.(interface{ As(any) bool }); ok && x.As(target) { return true } err = Unwrap(err) diff --git a/src/errors/wrap_test.go b/src/errors/wrap_test.go index a22fee2f04412..eb8314b04bb67 100644 --- a/src/errors/wrap_test.go +++ b/src/errors/wrap_test.go @@ -66,7 +66,7 @@ var poserPathErr = &fs.PathError{Op: "poser"} func (p *poser) Error() string { return p.msg } func (p *poser) Is(err error) bool { return p.f(err) } -func (p *poser) As(err interface{}) bool { +func (p *poser) As(err any) bool { switch x := err.(type) { case **poser: *x = p @@ -90,9 +90,9 @@ func TestAs(t *testing.T) { testCases := []struct { err error - target interface{} + target any match bool - want interface{} // value of target on match + want any // value of target on match }{{ nil, &errP, @@ -171,7 +171,7 @@ func TestAs(t *testing.T) { func TestAsValidation(t *testing.T) { var s string - testCases := []interface{}{ + testCases := []any{ nil, (*int)(nil), "error", diff --git a/src/expvar/expvar.go b/src/expvar/expvar.go index 13b5c99b6e536..8bbf41b151db2 100644 --- a/src/expvar/expvar.go +++ b/src/expvar/expvar.go @@ -130,7 +130,7 @@ func (v *Map) Init() *Map { v.keysMu.Lock() defer v.keysMu.Unlock() v.keys = v.keys[:0] - v.m.Range(func(k, _ interface{}) bool { + v.m.Range(func(k, _ any) bool { v.m.Delete(k) return true }) @@ -252,9 +252,9 @@ func (v *String) Set(value string) { // Func implements Var by calling the function // and formatting the returned value using JSON. -type Func func() interface{} +type Func func() any -func (f Func) Value() interface{} { +func (f Func) Value() any { return f() } @@ -350,11 +350,11 @@ func Handler() http.Handler { return http.HandlerFunc(expvarHandler) } -func cmdline() interface{} { +func cmdline() any { return os.Args } -func memstats() interface{} { +func memstats() any { stats := new(runtime.MemStats) runtime.ReadMemStats(stats) return *stats diff --git a/src/expvar/expvar_test.go b/src/expvar/expvar_test.go index 69b0a76058f8d..ba95a36066c39 100644 --- a/src/expvar/expvar_test.go +++ b/src/expvar/expvar_test.go @@ -242,12 +242,12 @@ func TestMapCounter(t *testing.T) { // colors.String() should be '{"red":3, "blue":4}', // though the order of red and blue could vary. s := colors.String() - var j interface{} + var j any err := json.Unmarshal([]byte(s), &j) if err != nil { t.Errorf("colors.String() isn't valid JSON: %v", err) } - m, ok := j.(map[string]interface{}) + m, ok := j.(map[string]any) if !ok { t.Error("colors.String() didn't produce a map.") } @@ -427,8 +427,8 @@ func BenchmarkMapAddDifferentSteadyState(b *testing.B) { func TestFunc(t *testing.T) { RemoveAll() - var x interface{} = []string{"a", "b"} - f := Func(func() interface{} { return x }) + var x any = []string{"a", "b"} + f := Func(func() any { return x }) if s, exp := f.String(), `["a","b"]`; s != exp { t.Errorf(`f.String() = %q, want %q`, s, exp) } diff --git a/src/flag/flag.go b/src/flag/flag.go index 86e16e5a612f3..4e2af450c5065 100644 --- a/src/flag/flag.go +++ b/src/flag/flag.go @@ -122,7 +122,7 @@ func (b *boolValue) Set(s string) error { return err } -func (b *boolValue) Get() interface{} { return bool(*b) } +func (b *boolValue) Get() any { return bool(*b) } func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) } @@ -152,7 +152,7 @@ func (i *intValue) Set(s string) error { return err } -func (i *intValue) Get() interface{} { return int(*i) } +func (i *intValue) Get() any { return int(*i) } func (i *intValue) String() string { return strconv.Itoa(int(*i)) } @@ -173,7 +173,7 @@ func (i *int64Value) Set(s string) error { return err } -func (i *int64Value) Get() interface{} { return int64(*i) } +func (i *int64Value) Get() any { return int64(*i) } func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) } @@ -194,7 +194,7 @@ func (i *uintValue) Set(s string) error { return err } -func (i *uintValue) Get() interface{} { return uint(*i) } +func (i *uintValue) Get() any { return uint(*i) } func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) } @@ -215,7 +215,7 @@ func (i *uint64Value) Set(s string) error { return err } -func (i *uint64Value) Get() interface{} { return uint64(*i) } +func (i *uint64Value) Get() any { return uint64(*i) } func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } @@ -232,7 +232,7 @@ func (s *stringValue) Set(val string) error { return nil } -func (s *stringValue) Get() interface{} { return string(*s) } +func (s *stringValue) Get() any { return string(*s) } func (s *stringValue) String() string { return string(*s) } @@ -253,7 +253,7 @@ func (f *float64Value) Set(s string) error { return err } -func (f *float64Value) Get() interface{} { return float64(*f) } +func (f *float64Value) Get() any { return float64(*f) } func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } @@ -274,7 +274,7 @@ func (d *durationValue) Set(s string) error { return err } -func (d *durationValue) Get() interface{} { return time.Duration(*d) } +func (d *durationValue) Get() any { return time.Duration(*d) } func (d *durationValue) String() string { return (*time.Duration)(d).String() } @@ -305,7 +305,7 @@ type Value interface { // by this package satisfy the Getter interface, except the type used by Func. type Getter interface { Value - Get() interface{} + Get() any } // ErrorHandling defines how FlagSet.Parse behaves if the parse fails. @@ -895,7 +895,7 @@ func Var(value Value, name string, usage string) { } // sprintf formats the message, prints it to output, and returns it. -func (f *FlagSet) sprintf(format string, a ...interface{}) string { +func (f *FlagSet) sprintf(format string, a ...any) string { msg := fmt.Sprintf(format, a...) fmt.Fprintln(f.Output(), msg) return msg @@ -903,7 +903,7 @@ func (f *FlagSet) sprintf(format string, a ...interface{}) string { // failf prints to standard error a formatted error and usage message and // returns the error. -func (f *FlagSet) failf(format string, a ...interface{}) error { +func (f *FlagSet) failf(format string, a ...any) error { msg := f.sprintf(format, a...) f.usage() return errors.New(msg) diff --git a/src/fmt/errors.go b/src/fmt/errors.go index 466a620353310..4f4daf19e1448 100644 --- a/src/fmt/errors.go +++ b/src/fmt/errors.go @@ -14,7 +14,7 @@ import "errors" // invalid to include more than one %w verb or to supply it with an operand // that does not implement the error interface. The %w verb is otherwise // a synonym for %v. -func Errorf(format string, a ...interface{}) error { +func Errorf(format string, a ...any) error { p := newPrinter() p.wrapErrs = true p.doPrintf(format, a) diff --git a/src/fmt/fmt_test.go b/src/fmt/fmt_test.go index 87fb32380946e..a4c65b8f5ee72 100644 --- a/src/fmt/fmt_test.go +++ b/src/fmt/fmt_test.go @@ -40,7 +40,7 @@ type ( ) func TestFmtInterface(t *testing.T) { - var i1 interface{} + var i1 any i1 = "abc" s := Sprintf("%s", i1) if s != "abc" { @@ -56,7 +56,7 @@ var ( intVar = 0 array = [5]int{1, 2, 3, 4, 5} - iarray = [4]interface{}{1, "hello", 2.5, nil} + iarray = [4]any{1, "hello", 2.5, nil} slice = array[:] islice = iarray[:] ) @@ -100,7 +100,7 @@ type S struct { } type SI struct { - I interface{} + I any } // P is a type with a String method with pointer receiver for testing %p. @@ -141,7 +141,7 @@ func (sf writeStringFormatter) Format(f State, c rune) { var fmtTests = []struct { fmt string - val interface{} + val any out string }{ {"%d", 12345, "12345"}, @@ -993,14 +993,14 @@ var fmtTests = []struct { // float and complex formatting should not change the padding width // for other elements. See issue 14642. - {"%06v", []interface{}{+10.0, 10}, "[000010 000010]"}, - {"%06v", []interface{}{-10.0, 10}, "[-00010 000010]"}, - {"%06v", []interface{}{+10.0 + 10i, 10}, "[(000010+00010i) 000010]"}, - {"%06v", []interface{}{-10.0 + 10i, 10}, "[(-00010+00010i) 000010]"}, + {"%06v", []any{+10.0, 10}, "[000010 000010]"}, + {"%06v", []any{-10.0, 10}, "[-00010 000010]"}, + {"%06v", []any{+10.0 + 10i, 10}, "[(000010+00010i) 000010]"}, + {"%06v", []any{-10.0 + 10i, 10}, "[(-00010+00010i) 000010]"}, // integer formatting should not alter padding for other elements. - {"%03.6v", []interface{}{1, 2.0, "x"}, "[000001 002 00x]"}, - {"%03.0v", []interface{}{0, 2.0, "x"}, "[ 002 000]"}, + {"%03.6v", []any{1, 2.0, "x"}, "[000001 002 00x]"}, + {"%03.0v", []any{0, 2.0, "x"}, "[ 002 000]"}, // Complex fmt used to leave the plus flag set for future entries in the array // causing +2+0i and +3+0i instead of 2+0i and 3+0i. @@ -1060,7 +1060,7 @@ var fmtTests = []struct { // Tests to check that not supported verbs generate an error string. {"%☠", nil, "%!☠()"}, - {"%☠", interface{}(nil), "%!☠()"}, + {"%☠", any(nil), "%!☠()"}, {"%☠", int(0), "%!☠(int=0)"}, {"%☠", uint(0), "%!☠(uint=0)"}, {"%☠", []byte{0, 1}, "[%!☠(uint8=0) %!☠(uint8=1)]"}, @@ -1077,8 +1077,8 @@ var fmtTests = []struct { {"%☠", func() {}, "%!☠(func()=0xPTR)"}, {"%☠", reflect.ValueOf(renamedInt(0)), "%!☠(fmt_test.renamedInt=0)"}, {"%☠", SI{renamedInt(0)}, "{%!☠(fmt_test.renamedInt=0)}"}, - {"%☠", &[]interface{}{I(1), G(2)}, "&[%!☠(fmt_test.I=1) %!☠(fmt_test.G=2)]"}, - {"%☠", SI{&[]interface{}{I(1), G(2)}}, "{%!☠(*[]interface {}=&[1 2])}"}, + {"%☠", &[]any{I(1), G(2)}, "&[%!☠(fmt_test.I=1) %!☠(fmt_test.G=2)]"}, + {"%☠", SI{&[]any{I(1), G(2)}}, "{%!☠(*[]interface {}=&[1 2])}"}, {"%☠", reflect.Value{}, ""}, {"%☠", map[float64]int{NaN: 1}, "map[%!☠(float64=NaN):%!☠(int=1)]"}, } @@ -1180,7 +1180,7 @@ func TestComplexFormatting(t *testing.T) { } } -type SE []interface{} // slice of empty; notational compactness. +type SE []any // slice of empty; notational compactness. var reorderTests = []struct { fmt string @@ -1267,7 +1267,7 @@ func BenchmarkSprintfTruncateString(b *testing.B) { } func BenchmarkSprintfTruncateBytes(b *testing.B) { - var bytes interface{} = []byte("日本語日本語日本語日本語") + var bytes any = []byte("日本語日本語日本語日本語") b.RunParallel(func(pb *testing.PB) { for pb.Next() { Sprintf("%.3s", bytes) @@ -1375,7 +1375,7 @@ func BenchmarkSprintfStringer(b *testing.B) { } func BenchmarkSprintfStructure(b *testing.B) { - s := &[]interface{}{SI{12345}, map[int]string{0: "hello"}} + s := &[]any{SI{12345}, map[int]string{0: "hello"}} b.RunParallel(func(pb *testing.PB) { for pb.Next() { Sprintf("%#v", s) @@ -1411,7 +1411,7 @@ func BenchmarkFprintfBytes(b *testing.B) { } func BenchmarkFprintIntNoAlloc(b *testing.B) { - var x interface{} = 123456 + var x any = 123456 var buf bytes.Buffer for i := 0; i < b.N; i++ { buf.Reset() @@ -1641,11 +1641,11 @@ func TestFormatterPrintln(t *testing.T) { } } -func args(a ...interface{}) []interface{} { return a } +func args(a ...any) []any { return a } var startests = []struct { fmt string - in []interface{} + in []any out string }{ {"%*d", args(4, 42), " 42"}, @@ -1687,7 +1687,7 @@ func TestWidthAndPrecision(t *testing.T) { // PanicS is a type that panics in String. type PanicS struct { - message interface{} + message any } // Value receiver. @@ -1697,7 +1697,7 @@ func (p PanicS) String() string { // PanicGo is a type that panics in GoString. type PanicGo struct { - message interface{} + message any } // Value receiver. @@ -1707,7 +1707,7 @@ func (p PanicGo) GoString() string { // PanicF is a type that panics in Format. type PanicF struct { - message interface{} + message any } // Value receiver. @@ -1717,7 +1717,7 @@ func (p PanicF) Format(f State, c rune) { var panictests = []struct { fmt string - in interface{} + in any out string }{ // String @@ -1729,7 +1729,7 @@ var panictests = []struct { {"%#v", PanicGo{io.ErrUnexpectedEOF}, "%!v(PANIC=GoString method: unexpected EOF)"}, {"%#v", PanicGo{3}, "%!v(PANIC=GoString method: 3)"}, // Issue 18282. catchPanic should not clear fmtFlags permanently. - {"%#v", []interface{}{PanicGo{3}, PanicGo{3}}, "[]interface {}{%!v(PANIC=GoString method: 3), %!v(PANIC=GoString method: 3)}"}, + {"%#v", []any{PanicGo{3}, PanicGo{3}}, "[]interface {}{%!v(PANIC=GoString method: 3), %!v(PANIC=GoString method: 3)}"}, // Format {"%s", (*PanicF)(nil), ""}, // nil pointer special case {"%s", PanicF{io.ErrUnexpectedEOF}, "%!s(PANIC=Format method: unexpected EOF)"}, @@ -1805,7 +1805,7 @@ func TestNilDoesNotBecomeTyped(t *testing.T) { var formatterFlagTests = []struct { in string - val interface{} + val any out string }{ // scalar values with the (unused by fmt) 'a' verb. diff --git a/src/fmt/print.go b/src/fmt/print.go index 698ab557a4a3f..1c37c3cb7b389 100644 --- a/src/fmt/print.go +++ b/src/fmt/print.go @@ -106,7 +106,7 @@ type pp struct { buf buffer // arg holds the current item, as an interface{}. - arg interface{} + arg any // value is used instead of arg for reflect values. value reflect.Value @@ -129,7 +129,7 @@ type pp struct { } var ppFree = sync.Pool{ - New: func() interface{} { return new(pp) }, + New: func() any { return new(pp) }, } // newPrinter allocates a new pp struct or grabs a cached one. @@ -199,7 +199,7 @@ func (p *pp) WriteString(s string) (ret int, err error) { // Fprintf formats according to a format specifier and writes to w. // It returns the number of bytes written and any write error encountered. -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { +func Fprintf(w io.Writer, format string, a ...any) (n int, err error) { p := newPrinter() p.doPrintf(format, a) n, err = w.Write(p.buf) @@ -209,12 +209,12 @@ func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. -func Printf(format string, a ...interface{}) (n int, err error) { +func Printf(format string, a ...any) (n int, err error) { return Fprintf(os.Stdout, format, a...) } // Sprintf formats according to a format specifier and returns the resulting string. -func Sprintf(format string, a ...interface{}) string { +func Sprintf(format string, a ...any) string { p := newPrinter() p.doPrintf(format, a) s := string(p.buf) @@ -227,7 +227,7 @@ func Sprintf(format string, a ...interface{}) string { // Fprint formats using the default formats for its operands and writes to w. // Spaces are added between operands when neither is a string. // It returns the number of bytes written and any write error encountered. -func Fprint(w io.Writer, a ...interface{}) (n int, err error) { +func Fprint(w io.Writer, a ...any) (n int, err error) { p := newPrinter() p.doPrint(a) n, err = w.Write(p.buf) @@ -238,13 +238,13 @@ func Fprint(w io.Writer, a ...interface{}) (n int, err error) { // Print formats using the default formats for its operands and writes to standard output. // Spaces are added between operands when neither is a string. // It returns the number of bytes written and any write error encountered. -func Print(a ...interface{}) (n int, err error) { +func Print(a ...any) (n int, err error) { return Fprint(os.Stdout, a...) } // Sprint formats using the default formats for its operands and returns the resulting string. // Spaces are added between operands when neither is a string. -func Sprint(a ...interface{}) string { +func Sprint(a ...any) string { p := newPrinter() p.doPrint(a) s := string(p.buf) @@ -259,7 +259,7 @@ func Sprint(a ...interface{}) string { // Fprintln formats using the default formats for its operands and writes to w. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. -func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { +func Fprintln(w io.Writer, a ...any) (n int, err error) { p := newPrinter() p.doPrintln(a) n, err = w.Write(p.buf) @@ -270,13 +270,13 @@ func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { // Println formats using the default formats for its operands and writes to standard output. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. -func Println(a ...interface{}) (n int, err error) { +func Println(a ...any) (n int, err error) { return Fprintln(os.Stdout, a...) } // Sprintln formats using the default formats for its operands and returns the resulting string. // Spaces are always added between operands and a newline is appended. -func Sprintln(a ...interface{}) string { +func Sprintln(a ...any) string { p := newPrinter() p.doPrintln(a) s := string(p.buf) @@ -533,7 +533,7 @@ func (p *pp) fmtPointer(value reflect.Value, verb rune) { } } -func (p *pp) catchPanic(arg interface{}, verb rune, method string) { +func (p *pp) catchPanic(arg any, verb rune, method string) { if err := recover(); err != nil { // If it's a nil pointer, just say "". The likeliest causes are a // Stringer that fails to guard against nil or a nil pointer for a @@ -631,7 +631,7 @@ func (p *pp) handleMethods(verb rune) (handled bool) { return false } -func (p *pp) printArg(arg interface{}, verb rune) { +func (p *pp) printArg(arg any, verb rune) { p.arg = arg p.value = reflect.Value{} @@ -886,7 +886,7 @@ func (p *pp) printValue(value reflect.Value, verb rune, depth int) { } // intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has integer type. -func intFromArg(a []interface{}, argNum int) (num int, isInt bool, newArgNum int) { +func intFromArg(a []any, argNum int) (num int, isInt bool, newArgNum int) { newArgNum = argNum if argNum < len(a) { num, isInt = a[argNum].(int) // Almost always OK. @@ -971,7 +971,7 @@ func (p *pp) missingArg(verb rune) { p.buf.writeString(missingString) } -func (p *pp) doPrintf(format string, a []interface{}) { +func (p *pp) doPrintf(format string, a []any) { end := len(format) argNum := 0 // we process one argument per non-trivial format afterIndex := false // previous item in format was an index like [3]. @@ -1146,7 +1146,7 @@ formatLoop: } } -func (p *pp) doPrint(a []interface{}) { +func (p *pp) doPrint(a []any) { prevString := false for argNum, arg := range a { isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String @@ -1161,7 +1161,7 @@ func (p *pp) doPrint(a []interface{}) { // doPrintln is like doPrint but always adds a space between arguments // and a newline after the last argument. -func (p *pp) doPrintln(a []interface{}) { +func (p *pp) doPrintln(a []any) { for argNum, arg := range a { if argNum > 0 { p.buf.writeByte(' ') diff --git a/src/fmt/scan.go b/src/fmt/scan.go index 18cb608f43ba2..d38610df35595 100644 --- a/src/fmt/scan.go +++ b/src/fmt/scan.go @@ -60,13 +60,13 @@ type Scanner interface { // space-separated values into successive arguments. Newlines count // as space. It returns the number of items successfully scanned. // If that is less than the number of arguments, err will report why. -func Scan(a ...interface{}) (n int, err error) { +func Scan(a ...any) (n int, err error) { return Fscan(os.Stdin, a...) } // Scanln is similar to Scan, but stops scanning at a newline and // after the final item there must be a newline or EOF. -func Scanln(a ...interface{}) (n int, err error) { +func Scanln(a ...any) (n int, err error) { return Fscanln(os.Stdin, a...) } @@ -77,7 +77,7 @@ func Scanln(a ...interface{}) (n int, err error) { // Newlines in the input must match newlines in the format. // The one exception: the verb %c always scans the next rune in the // input, even if it is a space (or tab etc.) or newline. -func Scanf(format string, a ...interface{}) (n int, err error) { +func Scanf(format string, a ...any) (n int, err error) { return Fscanf(os.Stdin, format, a...) } @@ -96,13 +96,13 @@ func (r *stringReader) Read(b []byte) (n int, err error) { // values into successive arguments. Newlines count as space. It // returns the number of items successfully scanned. If that is less // than the number of arguments, err will report why. -func Sscan(str string, a ...interface{}) (n int, err error) { +func Sscan(str string, a ...any) (n int, err error) { return Fscan((*stringReader)(&str), a...) } // Sscanln is similar to Sscan, but stops scanning at a newline and // after the final item there must be a newline or EOF. -func Sscanln(str string, a ...interface{}) (n int, err error) { +func Sscanln(str string, a ...any) (n int, err error) { return Fscanln((*stringReader)(&str), a...) } @@ -110,7 +110,7 @@ func Sscanln(str string, a ...interface{}) (n int, err error) { // values into successive arguments as determined by the format. It // returns the number of items successfully parsed. // Newlines in the input must match newlines in the format. -func Sscanf(str string, format string, a ...interface{}) (n int, err error) { +func Sscanf(str string, format string, a ...any) (n int, err error) { return Fscanf((*stringReader)(&str), format, a...) } @@ -118,7 +118,7 @@ func Sscanf(str string, format string, a ...interface{}) (n int, err error) { // values into successive arguments. Newlines count as space. It // returns the number of items successfully scanned. If that is less // than the number of arguments, err will report why. -func Fscan(r io.Reader, a ...interface{}) (n int, err error) { +func Fscan(r io.Reader, a ...any) (n int, err error) { s, old := newScanState(r, true, false) n, err = s.doScan(a) s.free(old) @@ -127,7 +127,7 @@ func Fscan(r io.Reader, a ...interface{}) (n int, err error) { // Fscanln is similar to Fscan, but stops scanning at a newline and // after the final item there must be a newline or EOF. -func Fscanln(r io.Reader, a ...interface{}) (n int, err error) { +func Fscanln(r io.Reader, a ...any) (n int, err error) { s, old := newScanState(r, false, true) n, err = s.doScan(a) s.free(old) @@ -138,7 +138,7 @@ func Fscanln(r io.Reader, a ...interface{}) (n int, err error) { // values into successive arguments as determined by the format. It // returns the number of items successfully parsed. // Newlines in the input must match newlines in the format. -func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error) { +func Fscanf(r io.Reader, format string, a ...any) (n int, err error) { s, old := newScanState(r, false, false) n, err = s.doScanf(format, a) s.free(old) @@ -376,7 +376,7 @@ func (r *readRune) UnreadRune() error { } var ssFree = sync.Pool{ - New: func() interface{} { return new(ss) }, + New: func() any { return new(ss) }, } // newScanState allocates a new ss struct or grab a cached one. @@ -950,7 +950,7 @@ func (s *ss) scanPercent() { } // scanOne scans a single value, deriving the scanner from the type of the argument. -func (s *ss) scanOne(verb rune, arg interface{}) { +func (s *ss) scanOne(verb rune, arg any) { s.buf = s.buf[:0] var err error // If the parameter has its own Scan method, use that. @@ -1067,7 +1067,7 @@ func errorHandler(errp *error) { } // doScan does the real work for scanning without a format string. -func (s *ss) doScan(a []interface{}) (numProcessed int, err error) { +func (s *ss) doScan(a []any) (numProcessed int, err error) { defer errorHandler(&err) for _, arg := range a { s.scanOne('v', arg) @@ -1178,7 +1178,7 @@ func (s *ss) advance(format string) (i int) { // doScanf does the real work when scanning with a format string. // At the moment, it handles only pointers to basic types. -func (s *ss) doScanf(format string, a []interface{}) (numProcessed int, err error) { +func (s *ss) doScanf(format string, a []any) (numProcessed int, err error) { defer errorHandler(&err) end := len(format) - 1 // We process one item per non-trivial format diff --git a/src/fmt/scan_test.go b/src/fmt/scan_test.go index 6b71b792ed1bb..da0dfd19a2d4f 100644 --- a/src/fmt/scan_test.go +++ b/src/fmt/scan_test.go @@ -21,22 +21,22 @@ import ( type ScanTest struct { text string - in interface{} - out interface{} + in any + out any } type ScanfTest struct { format string text string - in interface{} - out interface{} + in any + out any } type ScanfMultiTest struct { format string text string - in []interface{} - out []interface{} + in []any + out []any err string } @@ -444,7 +444,7 @@ var z IntString var r1, r2, r3 rune var multiTests = []ScanfMultiTest{ - {"", "", []interface{}{}, []interface{}{}, ""}, + {"", "", []any{}, []any{}, ""}, {"%d", "23", args(&i), args(23), ""}, {"%2s%3s", "22333", args(&s, &t), args("22", "333"), ""}, {"%2d%3d", "44555", args(&i, &j), args(44, 555), ""}, @@ -498,7 +498,7 @@ var readers = []struct { }}, } -func testScan(t *testing.T, f func(string) io.Reader, scan func(r io.Reader, a ...interface{}) (int, error)) { +func testScan(t *testing.T, f func(string) io.Reader, scan func(r io.Reader, a ...any) (int, error)) { for _, test := range scanTests { r := f(test.text) n, err := scan(r, test.in) @@ -637,7 +637,7 @@ func TestInf(t *testing.T) { } func testScanfMulti(t *testing.T, f func(string) io.Reader) { - sliceType := reflect.TypeOf(make([]interface{}, 1)) + sliceType := reflect.TypeOf(make([]any, 1)) for _, test := range multiTests { r := f(test.text) n, err := Fscanf(r, test.format, test.in...) @@ -836,7 +836,7 @@ func TestEOFAtEndOfInput(t *testing.T) { var eofTests = []struct { format string - v interface{} + v any }{ {"%s", &stringVal}, {"%q", &stringVal}, diff --git a/src/go/ast/print.go b/src/go/ast/print.go index b58683075cbca..85e6943928d69 100644 --- a/src/go/ast/print.go +++ b/src/go/ast/print.go @@ -36,17 +36,17 @@ func NotNilFilter(_ string, v reflect.Value) bool { // struct fields for which f(fieldname, fieldvalue) is true are // printed; all others are filtered from the output. Unexported // struct fields are never printed. -func Fprint(w io.Writer, fset *token.FileSet, x interface{}, f FieldFilter) error { +func Fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) error { return fprint(w, fset, x, f) } -func fprint(w io.Writer, fset *token.FileSet, x interface{}, f FieldFilter) (err error) { +func fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) (err error) { // setup printer p := printer{ output: w, fset: fset, filter: f, - ptrmap: make(map[interface{}]int), + ptrmap: make(map[any]int), last: '\n', // force printing of line number on first line } @@ -70,7 +70,7 @@ func fprint(w io.Writer, fset *token.FileSet, x interface{}, f FieldFilter) (err // Print prints x to standard output, skipping nil fields. // Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter). -func Print(fset *token.FileSet, x interface{}) error { +func Print(fset *token.FileSet, x any) error { return Fprint(os.Stdout, fset, x, NotNilFilter) } @@ -78,10 +78,10 @@ type printer struct { output io.Writer fset *token.FileSet filter FieldFilter - ptrmap map[interface{}]int // *T -> line number - indent int // current indentation level - last byte // the last byte processed by Write - line int // current line number + ptrmap map[any]int // *T -> line number + indent int // current indentation level + last byte // the last byte processed by Write + line int // current line number } var indent = []byte(". ") @@ -125,7 +125,7 @@ type localError struct { } // printf is a convenience wrapper that takes care of print errors. -func (p *printer) printf(format string, args ...interface{}) { +func (p *printer) printf(format string, args ...any) { if _, err := fmt.Fprintf(p, format, args...); err != nil { panic(localError{err}) } diff --git a/src/go/ast/print_test.go b/src/go/ast/print_test.go index 210f1643010c7..6691ccd63a315 100644 --- a/src/go/ast/print_test.go +++ b/src/go/ast/print_test.go @@ -11,7 +11,7 @@ import ( ) var tests = []struct { - x interface{} // x is printed as s + x any // x is printed as s s string }{ // basic types diff --git a/src/go/ast/resolve.go b/src/go/ast/resolve.go index c1830b5e4db30..126a27b18cdd9 100644 --- a/src/go/ast/resolve.go +++ b/src/go/ast/resolve.go @@ -22,7 +22,7 @@ func (p *pkgBuilder) error(pos token.Pos, msg string) { p.errors.Add(p.fset.Position(pos), msg) } -func (p *pkgBuilder) errorf(pos token.Pos, format string, args ...interface{}) { +func (p *pkgBuilder) errorf(pos token.Pos, format string, args ...any) { p.error(pos, fmt.Sprintf(format, args...)) } diff --git a/src/go/ast/scope.go b/src/go/ast/scope.go index a400c7152a668..d24a5f0e002fd 100644 --- a/src/go/ast/scope.go +++ b/src/go/ast/scope.go @@ -75,10 +75,10 @@ func (s *Scope) String() string { // type Object struct { Kind ObjKind - Name string // declared name - Decl interface{} // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil - Data interface{} // object-specific data; or nil - Type interface{} // placeholder for type information; may be nil + Name string // declared name + Decl any // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil + Data any // object-specific data; or nil + Type any // placeholder for type information; may be nil } // NewObj creates a new object of a given kind and name. diff --git a/src/go/constant/value.go b/src/go/constant/value.go index 014e873100de6..dee3bce9eef41 100644 --- a/src/go/constant/value.go +++ b/src/go/constant/value.go @@ -579,7 +579,7 @@ func Float64Val(x Value) (float64, bool) { // Float *big.Float or *big.Rat // everything else nil // -func Val(x Value) interface{} { +func Val(x Value) any { switch x := x.(type) { case boolVal: return bool(x) @@ -610,7 +610,7 @@ func Val(x Value) interface{} { // *big.Rat Float // anything else Unknown // -func Make(x interface{}) Value { +func Make(x any) Value { switch x := x.(type) { case bool: return boolVal(x) diff --git a/src/go/constant/value_test.go b/src/go/constant/value_test.go index ac179b3d8c210..e41315ee27c71 100644 --- a/src/go/constant/value_test.go +++ b/src/go/constant/value_test.go @@ -659,10 +659,10 @@ func TestMakeFloat64(t *testing.T) { type makeTestCase struct { kind Kind - arg, want interface{} + arg, want any } -func dup(k Kind, x interface{}) makeTestCase { return makeTestCase{k, x, x} } +func dup(k Kind, x any) makeTestCase { return makeTestCase{k, x, x} } func TestMake(t *testing.T) { for _, test := range []makeTestCase{ diff --git a/src/go/doc/doc.go b/src/go/doc/doc.go index 79d38998e7b51..5ab854d084b66 100644 --- a/src/go/doc/doc.go +++ b/src/go/doc/doc.go @@ -157,7 +157,7 @@ func New(pkg *ast.Package, importPath string, mode Mode) *Package { // NewFromFiles takes ownership of the AST files and may edit them, // unless the PreserveAST Mode bit is on. // -func NewFromFiles(fset *token.FileSet, files []*ast.File, importPath string, opts ...interface{}) (*Package, error) { +func NewFromFiles(fset *token.FileSet, files []*ast.File, importPath string, opts ...any) (*Package, error) { // Check for invalid API usage. if fset == nil { panic(fmt.Errorf("doc.NewFromFiles: no token.FileSet provided (fset == nil)")) diff --git a/src/go/doc/doc_test.go b/src/go/doc/doc_test.go index cbdca62aa1d11..3d17036f01f69 100644 --- a/src/go/doc/doc_test.go +++ b/src/go/doc/doc_test.go @@ -38,7 +38,7 @@ func readTemplate(filename string) *template.Template { return template.Must(t.ParseFiles(filepath.Join(dataDir, filename))) } -func nodeFmt(node interface{}, fset *token.FileSet) string { +func nodeFmt(node any, fset *token.FileSet) string { var buf bytes.Buffer printer.Fprint(&buf, fset, node) return strings.ReplaceAll(strings.TrimSpace(buf.String()), "\n", "\n\t") diff --git a/src/go/doc/testdata/benchmark.go b/src/go/doc/testdata/benchmark.go index 1d581f057e619..d27bf116aafa9 100644 --- a/src/go/doc/testdata/benchmark.go +++ b/src/go/doc/testdata/benchmark.go @@ -232,7 +232,7 @@ func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks [ runtime.GOMAXPROCS(procs) b := &B{ common: common{ - signal: make(chan interface{}), + signal: make(chan any), }, benchmark: Benchmark, } @@ -285,7 +285,7 @@ func (b *B) trimOutput() { func Benchmark(f func(b *B)) BenchmarkResult { b := &B{ common: common{ - signal: make(chan interface{}), + signal: make(chan any), }, benchmark: InternalBenchmark{"", f}, } diff --git a/src/go/doc/testdata/testing.0.golden b/src/go/doc/testdata/testing.0.golden index 83cf37cd3a9c3..61dac8bb66ca5 100644 --- a/src/go/doc/testdata/testing.0.golden +++ b/src/go/doc/testdata/testing.0.golden @@ -46,10 +46,10 @@ TYPES } // Error is equivalent to Log() followed by Fail(). - func (c *B) Error(args ...interface{}) + func (c *B) Error(args ...any) // Errorf is equivalent to Logf() followed by Fail(). - func (c *B) Errorf(format string, args ...interface{}) + func (c *B) Errorf(format string, args ...any) // Fail marks the function as having failed but continues ... func (c *B) Fail() @@ -61,16 +61,16 @@ TYPES func (c *B) Failed() bool // Fatal is equivalent to Log() followed by FailNow(). - func (c *B) Fatal(args ...interface{}) + func (c *B) Fatal(args ...any) // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *B) Fatalf(format string, args ...interface{}) + func (c *B) Fatalf(format string, args ...any) // Log formats its arguments using default formatting, analogous ... - func (c *B) Log(args ...interface{}) + func (c *B) Log(args ...any) // Logf formats its arguments according to the format, analogous ... - func (c *B) Logf(format string, args ...interface{}) + func (c *B) Logf(format string, args ...any) // ResetTimer sets the elapsed benchmark time to zero. It does not ... func (b *B) ResetTimer() @@ -125,10 +125,10 @@ TYPES } // Error is equivalent to Log() followed by Fail(). - func (c *T) Error(args ...interface{}) + func (c *T) Error(args ...any) // Errorf is equivalent to Logf() followed by Fail(). - func (c *T) Errorf(format string, args ...interface{}) + func (c *T) Errorf(format string, args ...any) // Fail marks the function as having failed but continues ... func (c *T) Fail() @@ -140,16 +140,16 @@ TYPES func (c *T) Failed() bool // Fatal is equivalent to Log() followed by FailNow(). - func (c *T) Fatal(args ...interface{}) + func (c *T) Fatal(args ...any) // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *T) Fatalf(format string, args ...interface{}) + func (c *T) Fatalf(format string, args ...any) // Log formats its arguments using default formatting, analogous ... - func (c *T) Log(args ...interface{}) + func (c *T) Log(args ...any) // Logf formats its arguments according to the format, analogous ... - func (c *T) Logf(format string, args ...interface{}) + func (c *T) Logf(format string, args ...any) // Parallel signals that this test is to be run in parallel with ... func (t *T) Parallel() diff --git a/src/go/doc/testdata/testing.1.golden b/src/go/doc/testdata/testing.1.golden index b9d14517a9cfe..1655af11a8cdd 100644 --- a/src/go/doc/testdata/testing.1.golden +++ b/src/go/doc/testdata/testing.1.golden @@ -119,10 +119,10 @@ TYPES } // Error is equivalent to Log() followed by Fail(). - func (c *B) Error(args ...interface{}) + func (c *B) Error(args ...any) // Errorf is equivalent to Logf() followed by Fail(). - func (c *B) Errorf(format string, args ...interface{}) + func (c *B) Errorf(format string, args ...any) // Fail marks the function as having failed but continues ... func (c *B) Fail() @@ -134,16 +134,16 @@ TYPES func (c *B) Failed() bool // Fatal is equivalent to Log() followed by FailNow(). - func (c *B) Fatal(args ...interface{}) + func (c *B) Fatal(args ...any) // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *B) Fatalf(format string, args ...interface{}) + func (c *B) Fatalf(format string, args ...any) // Log formats its arguments using default formatting, analogous ... - func (c *B) Log(args ...interface{}) + func (c *B) Log(args ...any) // Logf formats its arguments according to the format, analogous ... - func (c *B) Logf(format string, args ...interface{}) + func (c *B) Logf(format string, args ...any) // ResetTimer sets the elapsed benchmark time to zero. It does not ... func (b *B) ResetTimer() @@ -221,10 +221,10 @@ TYPES } // Error is equivalent to Log() followed by Fail(). - func (c *T) Error(args ...interface{}) + func (c *T) Error(args ...any) // Errorf is equivalent to Logf() followed by Fail(). - func (c *T) Errorf(format string, args ...interface{}) + func (c *T) Errorf(format string, args ...any) // Fail marks the function as having failed but continues ... func (c *T) Fail() @@ -236,16 +236,16 @@ TYPES func (c *T) Failed() bool // Fatal is equivalent to Log() followed by FailNow(). - func (c *T) Fatal(args ...interface{}) + func (c *T) Fatal(args ...any) // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *T) Fatalf(format string, args ...interface{}) + func (c *T) Fatalf(format string, args ...any) // Log formats its arguments using default formatting, analogous ... - func (c *T) Log(args ...interface{}) + func (c *T) Log(args ...any) // Logf formats its arguments according to the format, analogous ... - func (c *T) Logf(format string, args ...interface{}) + func (c *T) Logf(format string, args ...any) // Parallel signals that this test is to be run in parallel with ... func (t *T) Parallel() @@ -262,15 +262,15 @@ TYPES failed bool // Test or benchmark has failed. start time.Time // Time test or benchmark started duration time.Duration - self interface{} // To be sent on signal channel when done. - signal chan interface{} // Output for serial tests. + self any // To be sent on signal channel when done. + signal chan any // Output for serial tests. } // Error is equivalent to Log() followed by Fail(). - func (c *common) Error(args ...interface{}) + func (c *common) Error(args ...any) // Errorf is equivalent to Logf() followed by Fail(). - func (c *common) Errorf(format string, args ...interface{}) + func (c *common) Errorf(format string, args ...any) // Fail marks the function as having failed but continues ... func (c *common) Fail() @@ -282,16 +282,16 @@ TYPES func (c *common) Failed() bool // Fatal is equivalent to Log() followed by FailNow(). - func (c *common) Fatal(args ...interface{}) + func (c *common) Fatal(args ...any) // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *common) Fatalf(format string, args ...interface{}) + func (c *common) Fatalf(format string, args ...any) // Log formats its arguments using default formatting, analogous ... - func (c *common) Log(args ...interface{}) + func (c *common) Log(args ...any) // Logf formats its arguments according to the format, analogous ... - func (c *common) Logf(format string, args ...interface{}) + func (c *common) Logf(format string, args ...any) // log generates the output. It's always at the same stack depth. func (c *common) log(s string) diff --git a/src/go/doc/testdata/testing.2.golden b/src/go/doc/testdata/testing.2.golden index 83cf37cd3a9c3..61dac8bb66ca5 100644 --- a/src/go/doc/testdata/testing.2.golden +++ b/src/go/doc/testdata/testing.2.golden @@ -46,10 +46,10 @@ TYPES } // Error is equivalent to Log() followed by Fail(). - func (c *B) Error(args ...interface{}) + func (c *B) Error(args ...any) // Errorf is equivalent to Logf() followed by Fail(). - func (c *B) Errorf(format string, args ...interface{}) + func (c *B) Errorf(format string, args ...any) // Fail marks the function as having failed but continues ... func (c *B) Fail() @@ -61,16 +61,16 @@ TYPES func (c *B) Failed() bool // Fatal is equivalent to Log() followed by FailNow(). - func (c *B) Fatal(args ...interface{}) + func (c *B) Fatal(args ...any) // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *B) Fatalf(format string, args ...interface{}) + func (c *B) Fatalf(format string, args ...any) // Log formats its arguments using default formatting, analogous ... - func (c *B) Log(args ...interface{}) + func (c *B) Log(args ...any) // Logf formats its arguments according to the format, analogous ... - func (c *B) Logf(format string, args ...interface{}) + func (c *B) Logf(format string, args ...any) // ResetTimer sets the elapsed benchmark time to zero. It does not ... func (b *B) ResetTimer() @@ -125,10 +125,10 @@ TYPES } // Error is equivalent to Log() followed by Fail(). - func (c *T) Error(args ...interface{}) + func (c *T) Error(args ...any) // Errorf is equivalent to Logf() followed by Fail(). - func (c *T) Errorf(format string, args ...interface{}) + func (c *T) Errorf(format string, args ...any) // Fail marks the function as having failed but continues ... func (c *T) Fail() @@ -140,16 +140,16 @@ TYPES func (c *T) Failed() bool // Fatal is equivalent to Log() followed by FailNow(). - func (c *T) Fatal(args ...interface{}) + func (c *T) Fatal(args ...any) // Fatalf is equivalent to Logf() followed by FailNow(). - func (c *T) Fatalf(format string, args ...interface{}) + func (c *T) Fatalf(format string, args ...any) // Log formats its arguments using default formatting, analogous ... - func (c *T) Log(args ...interface{}) + func (c *T) Log(args ...any) // Logf formats its arguments according to the format, analogous ... - func (c *T) Logf(format string, args ...interface{}) + func (c *T) Logf(format string, args ...any) // Parallel signals that this test is to be run in parallel with ... func (t *T) Parallel() diff --git a/src/go/doc/testdata/testing.go b/src/go/doc/testdata/testing.go index 52810f7a564c1..80238df283a7e 100644 --- a/src/go/doc/testdata/testing.go +++ b/src/go/doc/testdata/testing.go @@ -77,8 +77,8 @@ type common struct { failed bool // Test or benchmark has failed. start time.Time // Time test or benchmark started duration time.Duration - self interface{} // To be sent on signal channel when done. - signal chan interface{} // Output for serial tests. + self any // To be sent on signal channel when done. + signal chan any // Output for serial tests. } // Short reports whether the -test.short flag is set. @@ -167,32 +167,32 @@ func (c *common) log(s string) { // Log formats its arguments using default formatting, analogous to Println(), // and records the text in the error log. -func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) } +func (c *common) Log(args ...any) { c.log(fmt.Sprintln(args...)) } // Logf formats its arguments according to the format, analogous to Printf(), // and records the text in the error log. -func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) } +func (c *common) Logf(format string, args ...any) { c.log(fmt.Sprintf(format, args...)) } // Error is equivalent to Log() followed by Fail(). -func (c *common) Error(args ...interface{}) { +func (c *common) Error(args ...any) { c.log(fmt.Sprintln(args...)) c.Fail() } // Errorf is equivalent to Logf() followed by Fail(). -func (c *common) Errorf(format string, args ...interface{}) { +func (c *common) Errorf(format string, args ...any) { c.log(fmt.Sprintf(format, args...)) c.Fail() } // Fatal is equivalent to Log() followed by FailNow(). -func (c *common) Fatal(args ...interface{}) { +func (c *common) Fatal(args ...any) { c.log(fmt.Sprintln(args...)) c.FailNow() } // Fatalf is equivalent to Logf() followed by FailNow(). -func (c *common) Fatalf(format string, args ...interface{}) { +func (c *common) Fatalf(format string, args ...any) { c.log(fmt.Sprintf(format, args...)) c.FailNow() } @@ -269,7 +269,7 @@ func RunTests(matchString func(pat, str string) (bool, error), tests []InternalT // If all tests pump to the same channel, a bug can occur where a test // kicks off a goroutine that Fails, yet the test still delivers a completion signal, // which skews the counting. - var collector = make(chan interface{}) + var collector = make(chan any) numParallel := 0 startParallel := make(chan bool) @@ -289,7 +289,7 @@ func RunTests(matchString func(pat, str string) (bool, error), tests []InternalT } t := &T{ common: common{ - signal: make(chan interface{}), + signal: make(chan any), }, name: testName, startParallel: startParallel, diff --git a/src/go/format/format.go b/src/go/format/format.go index a603d9630e679..ea8dd208238cc 100644 --- a/src/go/format/format.go +++ b/src/go/format/format.go @@ -51,7 +51,7 @@ const parserMode = parser.ParseComments // The function may return early (before the entire result is written) // and return a formatting error, for instance due to an incorrect AST. // -func Node(dst io.Writer, fset *token.FileSet, node interface{}) error { +func Node(dst io.Writer, fset *token.FileSet, node any) error { // Determine if we have a complete source file (file != nil). var file *ast.File var cnode *printer.CommentedNode diff --git a/src/go/internal/gccgoimporter/parser.go b/src/go/internal/gccgoimporter/parser.go index 267c9953e49a8..48335fa6d8fdb 100644 --- a/src/go/internal/gccgoimporter/parser.go +++ b/src/go/internal/gccgoimporter/parser.go @@ -80,7 +80,7 @@ func (e importError) Error() string { return fmt.Sprintf("import error %s (byte offset = %d): %s", e.pos, e.pos.Offset, e.err) } -func (p *parser) error(err interface{}) { +func (p *parser) error(err any) { if s, ok := err.(string); ok { err = errors.New(s) } @@ -88,7 +88,7 @@ func (p *parser) error(err interface{}) { panic(importError{p.scanner.Pos(), err.(error)}) } -func (p *parser) errorf(format string, args ...interface{}) { +func (p *parser) errorf(format string, args ...any) { p.error(fmt.Errorf(format, args...)) } @@ -474,7 +474,7 @@ func (p *parser) reserve(n int) { // used to resolve named types, or it can be a *types.Pointer, // used to resolve pointers to named types in case they are referenced // by embedded fields. -func (p *parser) update(t types.Type, nlist []interface{}) { +func (p *parser) update(t types.Type, nlist []any) { if t == reserved { p.errorf("internal error: update(%v) invoked on reserved", nlist) } @@ -509,7 +509,7 @@ func (p *parser) update(t types.Type, nlist []interface{}) { // NamedType = TypeName [ "=" ] Type { Method } . // TypeName = ExportedName . // Method = "func" "(" Param ")" Name ParamList ResultList [InlineBody] ";" . -func (p *parser) parseNamedType(nlist []interface{}) types.Type { +func (p *parser) parseNamedType(nlist []any) types.Type { pkg, name := p.parseExportedName() scope := pkg.Scope() obj := scope.Lookup(name) @@ -626,7 +626,7 @@ func (p *parser) parseInt() int { } // ArrayOrSliceType = "[" [ int ] "]" Type . -func (p *parser) parseArrayOrSliceType(pkg *types.Package, nlist []interface{}) types.Type { +func (p *parser) parseArrayOrSliceType(pkg *types.Package, nlist []any) types.Type { p.expect('[') if p.tok == ']' { p.next() @@ -649,7 +649,7 @@ func (p *parser) parseArrayOrSliceType(pkg *types.Package, nlist []interface{}) } // MapType = "map" "[" Type "]" Type . -func (p *parser) parseMapType(pkg *types.Package, nlist []interface{}) types.Type { +func (p *parser) parseMapType(pkg *types.Package, nlist []any) types.Type { p.expectKeyword("map") t := new(types.Map) @@ -665,7 +665,7 @@ func (p *parser) parseMapType(pkg *types.Package, nlist []interface{}) types.Typ } // ChanType = "chan" ["<-" | "-<"] Type . -func (p *parser) parseChanType(pkg *types.Package, nlist []interface{}) types.Type { +func (p *parser) parseChanType(pkg *types.Package, nlist []any) types.Type { p.expectKeyword("chan") t := new(types.Chan) @@ -692,7 +692,7 @@ func (p *parser) parseChanType(pkg *types.Package, nlist []interface{}) types.Ty } // StructType = "struct" "{" { Field } "}" . -func (p *parser) parseStructType(pkg *types.Package, nlist []interface{}) types.Type { +func (p *parser) parseStructType(pkg *types.Package, nlist []any) types.Type { p.expectKeyword("struct") t := new(types.Struct) @@ -759,7 +759,7 @@ func (p *parser) parseResultList(pkg *types.Package) *types.Tuple { } // FunctionType = ParamList ResultList . -func (p *parser) parseFunctionType(pkg *types.Package, nlist []interface{}) *types.Signature { +func (p *parser) parseFunctionType(pkg *types.Package, nlist []any) *types.Signature { t := new(types.Signature) p.update(t, nlist) @@ -799,7 +799,7 @@ func (p *parser) parseFunc(pkg *types.Package) *types.Func { } // InterfaceType = "interface" "{" { ("?" Type | Func) ";" } "}" . -func (p *parser) parseInterfaceType(pkg *types.Package, nlist []interface{}) types.Type { +func (p *parser) parseInterfaceType(pkg *types.Package, nlist []any) types.Type { p.expectKeyword("interface") t := new(types.Interface) @@ -828,7 +828,7 @@ func (p *parser) parseInterfaceType(pkg *types.Package, nlist []interface{}) typ } // PointerType = "*" ("any" | Type) . -func (p *parser) parsePointerType(pkg *types.Package, nlist []interface{}) types.Type { +func (p *parser) parsePointerType(pkg *types.Package, nlist []any) types.Type { p.expect('*') if p.tok == scanner.Ident { p.expectKeyword("any") @@ -846,7 +846,7 @@ func (p *parser) parsePointerType(pkg *types.Package, nlist []interface{}) types } // TypeSpec = NamedType | MapType | ChanType | StructType | InterfaceType | PointerType | ArrayOrSliceType | FunctionType . -func (p *parser) parseTypeSpec(pkg *types.Package, nlist []interface{}) types.Type { +func (p *parser) parseTypeSpec(pkg *types.Package, nlist []any) types.Type { switch p.tok { case scanner.String: return p.parseNamedType(nlist) @@ -935,14 +935,14 @@ func lookupBuiltinType(typ int) types.Type { // // parseType updates the type map to t for all type numbers n. // -func (p *parser) parseType(pkg *types.Package, n ...interface{}) types.Type { +func (p *parser) parseType(pkg *types.Package, n ...any) types.Type { p.expect('<') t, _ := p.parseTypeAfterAngle(pkg, n...) return t } // (*parser).Type after reading the "<". -func (p *parser) parseTypeAfterAngle(pkg *types.Package, n ...interface{}) (t types.Type, n1 int) { +func (p *parser) parseTypeAfterAngle(pkg *types.Package, n ...any) (t types.Type, n1 int) { p.expectKeyword("type") n1 = 0 @@ -985,7 +985,7 @@ func (p *parser) parseTypeAfterAngle(pkg *types.Package, n ...interface{}) (t ty // parseTypeExtended is identical to parseType, but if the type in // question is a saved type, returns the index as well as the type // pointer (index returned is zero if we parsed a builtin). -func (p *parser) parseTypeExtended(pkg *types.Package, n ...interface{}) (t types.Type, n1 int) { +func (p *parser) parseTypeExtended(pkg *types.Package, n ...any) (t types.Type, n1 int) { p.expect('<') t, n1 = p.parseTypeAfterAngle(pkg, n...) return @@ -1072,7 +1072,7 @@ func (p *parser) parseTypes(pkg *types.Package) { } // parseSavedType parses one saved type definition. -func (p *parser) parseSavedType(pkg *types.Package, i int, nlist []interface{}) { +func (p *parser) parseSavedType(pkg *types.Package, i int, nlist []any) { defer func(s *scanner.Scanner, tok rune, lit string) { p.scanner = s p.tok = tok diff --git a/src/go/internal/gcimporter/gcimporter_test.go b/src/go/internal/gcimporter/gcimporter_test.go index c0f4e3934b092..15a7b176bb792 100644 --- a/src/go/internal/gcimporter/gcimporter_test.go +++ b/src/go/internal/gcimporter/gcimporter_test.go @@ -390,7 +390,7 @@ var importedObjectTests = []struct { {"go/internal/gcimporter.FindPkg", "func FindPkg(path string, srcDir string) (filename string, id string)"}, // interfaces - {"context.Context", "type Context interface{Deadline() (deadline time.Time, ok bool); Done() <-chan struct{}; Err() error; Value(key interface{}) interface{}}"}, + {"context.Context", "type Context interface{Deadline() (deadline time.Time, ok bool); Done() <-chan struct{}; Err() error; Value(key any) any}"}, {"crypto.Decrypter", "type Decrypter interface{Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error); Public() PublicKey}"}, {"encoding.BinaryMarshaler", "type BinaryMarshaler interface{MarshalBinary() (data []byte, err error)}"}, {"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"}, diff --git a/src/go/internal/gcimporter/support.go b/src/go/internal/gcimporter/support.go index 965e5d88388af..61d1b46a68036 100644 --- a/src/go/internal/gcimporter/support.go +++ b/src/go/internal/gcimporter/support.go @@ -13,7 +13,7 @@ import ( "sync" ) -func errorf(format string, args ...interface{}) { +func errorf(format string, args ...any) { panic(fmt.Sprintf(format, args...)) } diff --git a/src/go/internal/gcimporter/testdata/exports.go b/src/go/internal/gcimporter/testdata/exports.go index 91598c03e35c0..3d5a8c9e39fe1 100644 --- a/src/go/internal/gcimporter/testdata/exports.go +++ b/src/go/internal/gcimporter/testdata/exports.go @@ -50,7 +50,7 @@ type ( _ *T10 } T11 map[int]string - T12 interface{} + T12 any T13 interface { m1() m2(int) float32 @@ -65,7 +65,7 @@ type ( T17 func(x int) T18 func() float32 T19 func() (x float32) - T20 func(...interface{}) + T20 func(...any) T21 struct{ next *T21 } T22 struct{ link *T23 } T23 struct{ link *T22 } @@ -86,6 +86,6 @@ func F1() {} func F2(x int) {} func F3() int { return 0 } func F4() float32 { return 0 } -func F5(a, b, c int, u, v, w struct{ x, y T1 }, more ...interface{}) (p, q, r chan<- T10) +func F5(a, b, c int, u, v, w struct{ x, y T1 }, more ...any) (p, q, r chan<- T10) func (p *T1) M1() diff --git a/src/go/parser/error_test.go b/src/go/parser/error_test.go index a45c897da3640..bedfc265b58f5 100644 --- a/src/go/parser/error_test.go +++ b/src/go/parser/error_test.go @@ -154,7 +154,7 @@ func compareErrors(t *testing.T, fset *token.FileSet, expected map[token.Pos]str } } -func checkErrors(t *testing.T, filename string, input interface{}, mode Mode, expectErrors bool) { +func checkErrors(t *testing.T, filename string, input any, mode Mode, expectErrors bool) { t.Helper() src, err := readSource(filename, input) if err != nil { diff --git a/src/go/parser/interface.go b/src/go/parser/interface.go index 85486d2f4b465..e4f8c281ea734 100644 --- a/src/go/parser/interface.go +++ b/src/go/parser/interface.go @@ -22,7 +22,7 @@ import ( // otherwise it returns an error. If src == nil, readSource returns // the result of reading the file specified by filename. // -func readSource(filename string, src interface{}) ([]byte, error) { +func readSource(filename string, src any) ([]byte, error) { if src != nil { switch s := src.(type) { case string: @@ -82,7 +82,7 @@ const ( // representing the fragments of erroneous source code). Multiple errors // are returned via a scanner.ErrorList which is sorted by source position. // -func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode) (f *ast.File, err error) { +func ParseFile(fset *token.FileSet, filename string, src any, mode Mode) (f *ast.File, err error) { if fset == nil { panic("parser.ParseFile: no token.FileSet provided (fset == nil)") } @@ -188,7 +188,7 @@ func ParseDir(fset *token.FileSet, path string, filter func(fs.FileInfo) bool, m // representing the fragments of erroneous source code). Multiple errors // are returned via a scanner.ErrorList which is sorted by source position. // -func ParseExprFrom(fset *token.FileSet, filename string, src interface{}, mode Mode) (expr ast.Expr, err error) { +func ParseExprFrom(fset *token.FileSet, filename string, src any, mode Mode) (expr ast.Expr, err error) { if fset == nil { panic("parser.ParseExprFrom: no token.FileSet provided (fset == nil)") } diff --git a/src/go/parser/parser.go b/src/go/parser/parser.go index 7c1a8be2fa458..e456e2930e3fa 100644 --- a/src/go/parser/parser.go +++ b/src/go/parser/parser.go @@ -82,7 +82,7 @@ func (p *parser) allowTypeSets() bool { return p.mode&typeparams.DisallowTypeSet // ---------------------------------------------------------------------------- // Parsing support -func (p *parser) printTrace(a ...interface{}) { +func (p *parser) printTrace(a ...any) { const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " const n = len(dots) pos := p.file.Position(p.pos) diff --git a/src/go/parser/resolver.go b/src/go/parser/resolver.go index 54732a7fd6f15..910ca0689c7ec 100644 --- a/src/go/parser/resolver.go +++ b/src/go/parser/resolver.go @@ -67,11 +67,11 @@ type resolver struct { targetStack [][]*ast.Ident // stack of unresolved labels } -func (r *resolver) dump(format string, args ...interface{}) { +func (r *resolver) dump(format string, args ...any) { fmt.Println(">>> " + r.sprintf(format, args...)) } -func (r *resolver) sprintf(format string, args ...interface{}) string { +func (r *resolver) sprintf(format string, args ...any) string { for i, arg := range args { switch arg := arg.(type) { case token.Pos: @@ -115,7 +115,7 @@ func (r *resolver) closeLabelScope() { r.labelScope = r.labelScope.Outer } -func (r *resolver) declare(decl, data interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) { +func (r *resolver) declare(decl, data any, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) { for _, ident := range idents { assert(ident.Obj == nil, "identifier already declared or resolved") obj := ast.NewObj(kind, ident.Name) diff --git a/src/go/printer/printer.go b/src/go/printer/printer.go index 2f41e7bf72f6b..e4679b0021d91 100644 --- a/src/go/printer/printer.go +++ b/src/go/printer/printer.go @@ -104,7 +104,7 @@ func (p *printer) init(cfg *Config, fset *token.FileSet, nodeSizes map[ast.Node] p.cachedPos = -1 } -func (p *printer) internalError(msg ...interface{}) { +func (p *printer) internalError(msg ...any) { if debug { fmt.Print(p.pos.String() + ": ") fmt.Println(msg...) @@ -878,7 +878,7 @@ func mayCombine(prev token.Token, next byte) (b bool) { // space for best comment placement. Then, any leftover whitespace is // printed, followed by the actual token. // -func (p *printer) print(args ...interface{}) { +func (p *printer) print(args ...any) { for _, arg := range args { // information about the current arg var data string @@ -1075,7 +1075,7 @@ func getLastComment(n ast.Node) *ast.CommentGroup { return nil } -func (p *printer) printNode(node interface{}) error { +func (p *printer) printNode(node any) error { // unpack *CommentedNode, if any var comments []*ast.CommentGroup if cnode, ok := node.(*CommentedNode); ok { @@ -1309,7 +1309,7 @@ type Config struct { } // fprint implements Fprint and takes a nodesSizes map for setting up the printer state. -func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{}, nodeSizes map[ast.Node]int) (err error) { +func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node any, nodeSizes map[ast.Node]int) (err error) { // print node var p printer p.init(cfg, fset, nodeSizes) @@ -1365,7 +1365,7 @@ func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{ // It may be provided as argument to any of the Fprint functions. // type CommentedNode struct { - Node interface{} // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt + Node any // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt Comments []*ast.CommentGroup } @@ -1374,7 +1374,7 @@ type CommentedNode struct { // The node type must be *ast.File, *CommentedNode, []ast.Decl, []ast.Stmt, // or assignment-compatible to ast.Expr, ast.Decl, ast.Spec, or ast.Stmt. // -func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{}) error { +func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node any) error { return cfg.fprint(output, fset, node, make(map[ast.Node]int)) } @@ -1383,6 +1383,6 @@ func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{ // Note that gofmt uses tabs for indentation but spaces for alignment; // use format.Node (package go/format) for output that matches gofmt. // -func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error { +func Fprint(output io.Writer, fset *token.FileSet, node any) error { return (&Config{Tabwidth: 8}).Fprint(output, fset, node) } diff --git a/src/go/printer/testdata/parser.go b/src/go/printer/testdata/parser.go index fc2812adee0c3..7e8379739c6dc 100644 --- a/src/go/printer/testdata/parser.go +++ b/src/go/printer/testdata/parser.go @@ -122,7 +122,7 @@ func (p *parser) closeLabelScope() { p.labelScope = p.labelScope.Outer } -func (p *parser) declare(decl interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) { +func (p *parser) declare(decl any, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) { for _, ident := range idents { assert(ident.Obj == nil, "identifier already declared or resolved") if ident.Name != "_" { @@ -200,7 +200,7 @@ func (p *parser) resolve(x ast.Expr) { // ---------------------------------------------------------------------------- // Parsing support -func (p *parser) printTrace(a ...interface{}) { +func (p *parser) printTrace(a ...any) { const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " + ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " const n = uint(len(dots)) diff --git a/src/go/scanner/scanner.go b/src/go/scanner/scanner.go index ca4b5264cfedf..23d8db9d1ccdf 100644 --- a/src/go/scanner/scanner.go +++ b/src/go/scanner/scanner.go @@ -155,7 +155,7 @@ func (s *Scanner) error(offs int, msg string) { s.ErrorCount++ } -func (s *Scanner) errorf(offs int, format string, args ...interface{}) { +func (s *Scanner) errorf(offs int, format string, args ...any) { s.error(offs, fmt.Sprintf(format, args...)) } diff --git a/src/go/token/serialize.go b/src/go/token/serialize.go index d0ea34517a442..ffb69908b91f2 100644 --- a/src/go/token/serialize.go +++ b/src/go/token/serialize.go @@ -19,7 +19,7 @@ type serializedFileSet struct { } // Read calls decode to deserialize a file set into s; s must not be nil. -func (s *FileSet) Read(decode func(interface{}) error) error { +func (s *FileSet) Read(decode func(any) error) error { var ss serializedFileSet if err := decode(&ss); err != nil { return err @@ -47,7 +47,7 @@ func (s *FileSet) Read(decode func(interface{}) error) error { } // Write calls encode to serialize the file set s. -func (s *FileSet) Write(encode func(interface{}) error) error { +func (s *FileSet) Write(encode func(any) error) error { var ss serializedFileSet s.mutex.Lock() diff --git a/src/go/token/serialize_test.go b/src/go/token/serialize_test.go index 4e925adb6f264..4aa0b0da2600f 100644 --- a/src/go/token/serialize_test.go +++ b/src/go/token/serialize_test.go @@ -70,7 +70,7 @@ func equal(p, q *FileSet) error { func checkSerialize(t *testing.T, p *FileSet) { var buf bytes.Buffer - encode := func(x interface{}) error { + encode := func(x any) error { return gob.NewEncoder(&buf).Encode(x) } if err := p.Write(encode); err != nil { @@ -78,7 +78,7 @@ func checkSerialize(t *testing.T, p *FileSet) { return } q := NewFileSet() - decode := func(x interface{}) error { + decode := func(x any) error { return gob.NewDecoder(&buf).Decode(x) } if err := q.Read(decode); err != nil { diff --git a/src/go/types/check.go b/src/go/types/check.go index d967c0bd25115..2dd38e2e1e406 100644 --- a/src/go/types/check.go +++ b/src/go/types/check.go @@ -90,7 +90,7 @@ type action struct { // If debug is set, describef sets a printf-formatted description for action a. // Otherwise, it is a no-op. -func (a *action) describef(pos positioner, format string, args ...interface{}) { +func (a *action) describef(pos positioner, format string, args ...any) { if debug { a.desc = &actionDesc{pos, format, args} } @@ -101,7 +101,7 @@ func (a *action) describef(pos positioner, format string, args ...interface{}) { type actionDesc struct { pos positioner format string - args []interface{} + args []any } // A Checker maintains the state of the type checker. diff --git a/src/go/types/conversions.go b/src/go/types/conversions.go index fb3771635d33c..a5b359e5394c3 100644 --- a/src/go/types/conversions.go +++ b/src/go/types/conversions.go @@ -203,7 +203,7 @@ func (x *operand) convertibleTo(check *Checker, T Type, cause *string) bool { return false } - errorf := func(format string, args ...interface{}) { + errorf := func(format string, args ...any) { if check != nil && cause != nil { msg := check.sprintf(format, args...) if *cause != "" { diff --git a/src/go/types/errors.go b/src/go/types/errors.go index 92002add13cc4..81c62a82f0e44 100644 --- a/src/go/types/errors.go +++ b/src/go/types/errors.go @@ -62,11 +62,11 @@ func (check *Checker) markImports(pkg *Package) { } } -func (check *Checker) sprintf(format string, args ...interface{}) string { +func (check *Checker) sprintf(format string, args ...any) string { return sprintf(check.fset, check.qualifier, false, format, args...) } -func sprintf(fset *token.FileSet, qf Qualifier, debug bool, format string, args ...interface{}) string { +func sprintf(fset *token.FileSet, qf Qualifier, debug bool, format string, args ...any) string { for i, arg := range args { switch a := arg.(type) { case nil: @@ -91,7 +91,7 @@ func sprintf(fset *token.FileSet, qf Qualifier, debug bool, format string, args return fmt.Sprintf(format, args...) } -func (check *Checker) trace(pos token.Pos, format string, args ...interface{}) { +func (check *Checker) trace(pos token.Pos, format string, args ...any) { fmt.Printf("%s:\t%s%s\n", check.fset.Position(pos), strings.Repeat(". ", check.indent), @@ -100,7 +100,7 @@ func (check *Checker) trace(pos token.Pos, format string, args ...interface{}) { } // dump is only needed for debugging -func (check *Checker) dump(format string, args ...interface{}) { +func (check *Checker) dump(format string, args ...any) { fmt.Println(sprintf(check.fset, check.qualifier, true, format, args...)) } @@ -170,7 +170,7 @@ func (check *Checker) newError(at positioner, code errorCode, soft bool, msg str } // newErrorf creates a new Error, but does not handle it. -func (check *Checker) newErrorf(at positioner, code errorCode, soft bool, format string, args ...interface{}) error { +func (check *Checker) newErrorf(at positioner, code errorCode, soft bool, format string, args ...any) error { msg := check.sprintf(format, args...) return check.newError(at, code, soft, msg) } @@ -179,23 +179,23 @@ func (check *Checker) error(at positioner, code errorCode, msg string) { check.err(check.newError(at, code, false, msg)) } -func (check *Checker) errorf(at positioner, code errorCode, format string, args ...interface{}) { +func (check *Checker) errorf(at positioner, code errorCode, format string, args ...any) { check.error(at, code, check.sprintf(format, args...)) } -func (check *Checker) softErrorf(at positioner, code errorCode, format string, args ...interface{}) { +func (check *Checker) softErrorf(at positioner, code errorCode, format string, args ...any) { check.err(check.newErrorf(at, code, true, format, args...)) } -func (check *Checker) invalidAST(at positioner, format string, args ...interface{}) { +func (check *Checker) invalidAST(at positioner, format string, args ...any) { check.errorf(at, 0, "invalid AST: "+format, args...) } -func (check *Checker) invalidArg(at positioner, code errorCode, format string, args ...interface{}) { +func (check *Checker) invalidArg(at positioner, code errorCode, format string, args ...any) { check.errorf(at, code, "invalid argument: "+format, args...) } -func (check *Checker) invalidOp(at positioner, code errorCode, format string, args ...interface{}) { +func (check *Checker) invalidOp(at positioner, code errorCode, format string, args ...any) { check.errorf(at, code, "invalid operation: "+format, args...) } diff --git a/src/go/types/eval_test.go b/src/go/types/eval_test.go index 345bd14305935..b0745c16d9729 100644 --- a/src/go/types/eval_test.go +++ b/src/go/types/eval_test.go @@ -111,7 +111,7 @@ func TestEvalPos(t *testing.T) { x = a + len(s) return float64(x) /* true => true, untyped bool */ - /* fmt.Println => , func(a ...interface{}) (n int, err error) */ + /* fmt.Println => , func(a ...any) (n int, err error) */ /* c => 3, untyped float */ /* T => , p.T */ /* a => , int */ @@ -218,7 +218,7 @@ type T []int type S struct{ X int } func f(a int, s string) S { - /* fmt.Println => func fmt.Println(a ...interface{}) (n int, err error) */ + /* fmt.Println => func fmt.Println(a ...any) (n int, err error) */ /* fmt.Stringer.String => func (fmt.Stringer).String() string */ fmt.Println("calling f") diff --git a/src/go/types/expr.go b/src/go/types/expr.go index dd18abaf132ca..452e9ab598ab8 100644 --- a/src/go/types/expr.go +++ b/src/go/types/expr.go @@ -1354,7 +1354,7 @@ func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind { check.error(e, _InvalidTypeCycle, "illegal cycle in type declaration") goto Error } - visited := make(map[interface{}][]Type, len(e.Elts)) + visited := make(map[any][]Type, len(e.Elts)) for _, e := range e.Elts { kv, _ := e.(*ast.KeyValueExpr) if kv == nil { @@ -1542,7 +1542,7 @@ Error: return statement // avoid follow-up errors } -func keyVal(x constant.Value) interface{} { +func keyVal(x constant.Value) any { switch x.Kind() { case constant.Bool: return constant.BoolVal(x) diff --git a/src/go/types/gotype.go b/src/go/types/gotype.go index 1126b73810cf3..5d27bb7a077f9 100644 --- a/src/go/types/gotype.go +++ b/src/go/types/gotype.go @@ -179,7 +179,7 @@ func report(err error) { } // parse may be called concurrently -func parse(filename string, src interface{}) (*ast.File, error) { +func parse(filename string, src any) (*ast.File, error) { if *verbose { fmt.Println(filename) } diff --git a/src/go/types/hilbert_test.go b/src/go/types/hilbert_test.go index 77954d2f8b934..7d0f58ea40b59 100644 --- a/src/go/types/hilbert_test.go +++ b/src/go/types/hilbert_test.go @@ -84,7 +84,7 @@ type gen struct { bytes.Buffer } -func (g *gen) p(format string, args ...interface{}) { +func (g *gen) p(format string, args ...any) { fmt.Fprintf(&g.Buffer, format, args...) } diff --git a/src/go/types/initorder.go b/src/go/types/initorder.go index 27595ae233f82..1118b58f7bac2 100644 --- a/src/go/types/initorder.go +++ b/src/go/types/initorder.go @@ -304,11 +304,11 @@ func (a nodeQueue) Less(i, j int) bool { return x.ndeps < y.ndeps || x.ndeps == y.ndeps && x.obj.order() < y.obj.order() } -func (a *nodeQueue) Push(x interface{}) { +func (a *nodeQueue) Push(x any) { panic("unreachable") } -func (a *nodeQueue) Pop() interface{} { +func (a *nodeQueue) Pop() any { n := len(*a) x := (*a)[n-1] x.index = -1 // for safety diff --git a/src/go/types/instantiate.go b/src/go/types/instantiate.go index e91d08cc5ee44..e8748975c9150 100644 --- a/src/go/types/instantiate.go +++ b/src/go/types/instantiate.go @@ -164,7 +164,7 @@ func (check *Checker) implements(V, T Type, qf Qualifier) error { return nil } - errorf := func(format string, args ...interface{}) error { + errorf := func(format string, args ...any) error { return errors.New(sprintf(nil, qf, false, format, args...)) } diff --git a/src/go/types/operand.go b/src/go/types/operand.go index c35b1650be264..06ecbf14102ef 100644 --- a/src/go/types/operand.go +++ b/src/go/types/operand.go @@ -337,7 +337,7 @@ func (x *operand) assignableTo(check *Checker, T Type, reason *string) (bool, er return false, _IncompatibleAssign } - errorf := func(format string, args ...interface{}) { + errorf := func(format string, args ...any) { if check != nil && reason != nil { msg := check.sprintf(format, args...) if *reason != "" { diff --git a/src/go/types/sizeof_test.go b/src/go/types/sizeof_test.go index 5b7ee8bb7883d..69571d1159d06 100644 --- a/src/go/types/sizeof_test.go +++ b/src/go/types/sizeof_test.go @@ -14,9 +14,9 @@ func TestSizeof(t *testing.T) { const _64bit = ^uint(0)>>32 != 0 var tests = []struct { - val interface{} // type as a value - _32bit uintptr // size on 32bit platforms - _64bit uintptr // size on 64bit platforms + val any // type as a value + _32bit uintptr // size on 32bit platforms + _64bit uintptr // size on 64bit platforms }{ // Types {Basic{}, 16, 32}, diff --git a/src/go/types/stdlib_test.go b/src/go/types/stdlib_test.go index 687b80540a438..5e5e09562ac5a 100644 --- a/src/go/types/stdlib_test.go +++ b/src/go/types/stdlib_test.go @@ -296,7 +296,7 @@ func pkgFilenames(dir string) ([]string, error) { return filenames, nil } -func walkPkgDirs(dir string, pkgh func(dir string, filenames []string), errh func(args ...interface{})) time.Duration { +func walkPkgDirs(dir string, pkgh func(dir string, filenames []string), errh func(args ...any)) time.Duration { w := walker{time.Now(), 10 * time.Millisecond, pkgh, errh} w.walk(dir) return time.Since(w.start) @@ -306,7 +306,7 @@ type walker struct { start time.Time dmax time.Duration pkgh func(dir string, filenames []string) - errh func(args ...interface{}) + errh func(args ...any) } func (w *walker) walk(dir string) { diff --git a/src/go/types/stmt.go b/src/go/types/stmt.go index 06c9d3175db3c..8621d2800a54a 100644 --- a/src/go/types/stmt.go +++ b/src/go/types/stmt.go @@ -193,7 +193,7 @@ func (check *Checker) suspendedCall(keyword string, call *ast.CallExpr) { } // goVal returns the Go value for val, or nil. -func goVal(val constant.Value) interface{} { +func goVal(val constant.Value) any { // val should exist, but be conservative and check if val == nil { return nil @@ -227,7 +227,7 @@ func goVal(val constant.Value) interface{} { // types we need to also check the value's types (e.g., byte(1) vs myByte(1)) // when the switch expression is of interface type. type ( - valueMap map[interface{}][]valueType // underlying Go value -> valueType + valueMap map[any][]valueType // underlying Go value -> valueType valueType struct { pos token.Pos typ Type diff --git a/src/go/types/subst.go b/src/go/types/subst.go index 04eb3a6215577..169540365b69b 100644 --- a/src/go/types/subst.go +++ b/src/go/types/subst.go @@ -156,13 +156,13 @@ func (subst *subster) typ(typ Type) Type { case *Named: // dump is for debugging - dump := func(string, ...interface{}) {} + dump := func(string, ...any) {} if subst.check != nil && trace { subst.check.indent++ defer func() { subst.check.indent-- }() - dump = func(format string, args ...interface{}) { + dump = func(format string, args ...any) { subst.check.trace(subst.pos, format, args...) } } diff --git a/src/html/template/content.go b/src/html/template/content.go index 232ba199f3596..b104267177e1c 100644 --- a/src/html/template/content.go +++ b/src/html/template/content.go @@ -112,7 +112,7 @@ const ( // indirect returns the value, after dereferencing as many times // as necessary to reach the base type (or nil). -func indirect(a interface{}) interface{} { +func indirect(a any) any { if a == nil { return nil } @@ -135,7 +135,7 @@ var ( // indirectToStringerOrError returns the value, after dereferencing as many times // as necessary to reach the base type (or nil) or an implementation of fmt.Stringer // or error, -func indirectToStringerOrError(a interface{}) interface{} { +func indirectToStringerOrError(a any) any { if a == nil { return nil } @@ -148,7 +148,7 @@ func indirectToStringerOrError(a interface{}) interface{} { // stringify converts its arguments to a string and the type of the content. // All pointers are dereferenced, as in the text/template package. -func stringify(args ...interface{}) (string, contentType) { +func stringify(args ...any) (string, contentType) { if len(args) == 1 { switch s := indirect(args[0]).(type) { case string: diff --git a/src/html/template/content_test.go b/src/html/template/content_test.go index b7a39d4814b6f..497264ea329cc 100644 --- a/src/html/template/content_test.go +++ b/src/html/template/content_test.go @@ -12,7 +12,7 @@ import ( ) func TestTypedContent(t *testing.T) { - data := []interface{}{ + data := []any{ ` "foo%" O'Reilly &bar;`, CSS(`a[href =~ "//example.com"]#foo`), HTML(`Hello, World &tc!`), @@ -449,7 +449,7 @@ func TestEscapingNilNonemptyInterfaces(t *testing.T) { // A non-empty interface should print like an empty interface. want := new(bytes.Buffer) - data := struct{ E interface{} }{} + data := struct{ E any }{} tmpl.Execute(want, data) if !bytes.Equal(want.Bytes(), got.Bytes()) { diff --git a/src/html/template/css.go b/src/html/template/css.go index eb92fc92b55ea..890a0c6b227fe 100644 --- a/src/html/template/css.go +++ b/src/html/template/css.go @@ -155,7 +155,7 @@ func isCSSSpace(b byte) bool { } // cssEscaper escapes HTML and CSS special characters using \+ escapes. -func cssEscaper(args ...interface{}) string { +func cssEscaper(args ...any) string { s, _ := stringify(args...) var b strings.Builder r, w, written := rune(0), 0, 0 @@ -218,7 +218,7 @@ var mozBindingBytes = []byte("mozbinding") // (inherit, blue), and colors (#888). // It filters out unsafe values, such as those that affect token boundaries, // and anything that might execute scripts. -func cssValueFilter(args ...interface{}) string { +func cssValueFilter(args ...any) string { s, t := stringify(args...) if t == contentTypeCSS { return s diff --git a/src/html/template/error.go b/src/html/template/error.go index 0e527063ea62a..6bb5a2027f677 100644 --- a/src/html/template/error.go +++ b/src/html/template/error.go @@ -228,6 +228,6 @@ func (e *Error) Error() string { // errorf creates an error given a format string f and args. // The template Name still needs to be supplied. -func errorf(k ErrorCode, node parse.Node, line int, f string, args ...interface{}) *Error { +func errorf(k ErrorCode, node parse.Node, line int, f string, args ...any) *Error { return &Error{k, node, "", line, fmt.Sprintf(f, args...)} } diff --git a/src/html/template/escape.go b/src/html/template/escape.go index 6dea79c7b55fa..2b11526f52b69 100644 --- a/src/html/template/escape.go +++ b/src/html/template/escape.go @@ -45,7 +45,7 @@ func escapeTemplate(tmpl *Template, node parse.Node, name string) error { // evalArgs formats the list of arguments into a string. It is equivalent to // fmt.Sprint(args...), except that it deferences all pointers. -func evalArgs(args ...interface{}) string { +func evalArgs(args ...any) string { // Optimization for simple common case of a single string argument. if len(args) == 1 { if s, ok := args[0].(string); ok { @@ -934,7 +934,7 @@ func HTMLEscapeString(s string) string { // HTMLEscaper returns the escaped HTML equivalent of the textual // representation of its arguments. -func HTMLEscaper(args ...interface{}) string { +func HTMLEscaper(args ...any) string { return template.HTMLEscaper(args...) } @@ -950,12 +950,12 @@ func JSEscapeString(s string) string { // JSEscaper returns the escaped JavaScript equivalent of the textual // representation of its arguments. -func JSEscaper(args ...interface{}) string { +func JSEscaper(args ...any) string { return template.JSEscaper(args...) } // URLQueryEscaper returns the escaped value of the textual representation of // its arguments in a form suitable for embedding in a URL query. -func URLQueryEscaper(args ...interface{}) string { +func URLQueryEscaper(args ...any) string { return template.URLQueryEscaper(args...) } diff --git a/src/html/template/escape_test.go b/src/html/template/escape_test.go index 3b0aa8c846606..58f3f271b7a5c 100644 --- a/src/html/template/escape_test.go +++ b/src/html/template/escape_test.go @@ -35,8 +35,8 @@ func TestEscape(t *testing.T) { A, E []string B, M json.Marshaler N int - U interface{} // untyped nil - Z *int // typed nil + U any // untyped nil + Z *int // typed nil W HTML }{ F: false, @@ -858,7 +858,7 @@ func TestEscapeSet(t *testing.T) { // pred is a template function that returns the predecessor of a // natural number for testing recursive templates. - fns := FuncMap{"pred": func(a ...interface{}) (interface{}, error) { + fns := FuncMap{"pred": func(a ...any) (any, error) { if len(a) == 1 { if i, _ := a[0].(int); i > 0 { return i - 1, nil @@ -1788,7 +1788,7 @@ func TestEscapeSetErrorsNotIgnorable(t *testing.T) { } func TestRedundantFuncs(t *testing.T) { - inputs := []interface{}{ + inputs := []any{ "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" + "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" + ` !"#$%&'()*+,-./` + @@ -1808,9 +1808,9 @@ func TestRedundantFuncs(t *testing.T) { } for n0, m := range redundantFuncs { - f0 := funcMap[n0].(func(...interface{}) string) + f0 := funcMap[n0].(func(...any) string) for n1 := range m { - f1 := funcMap[n1].(func(...interface{}) string) + f1 := funcMap[n1].(func(...any) string) for _, input := range inputs { want := f0(input) if got := f1(want); want != got { diff --git a/src/html/template/example_test.go b/src/html/template/example_test.go index 6cf936f2709f3..605b25f41dbec 100644 --- a/src/html/template/example_test.go +++ b/src/html/template/example_test.go @@ -98,7 +98,7 @@ func Example_autoescaping() { func Example_escape() { const s = `"Fran & Freddie's Diner" ` - v := []interface{}{`"Fran & Freddie's Diner"`, ' ', ``} + v := []any{`"Fran & Freddie's Diner"`, ' ', ``} fmt.Println(template.HTMLEscapeString(s)) template.HTMLEscape(os.Stdout, []byte(s)) diff --git a/src/html/template/exec_test.go b/src/html/template/exec_test.go index 523340bac9591..6cf710efabc4f 100644 --- a/src/html/template/exec_test.go +++ b/src/html/template/exec_test.go @@ -49,7 +49,7 @@ type T struct { MSI map[string]int MSIone map[string]int // one element, for deterministic output MSIEmpty map[string]int - MXI map[interface{}]int + MXI map[any]int MII map[int]int MI32S map[int32]string MI64S map[int64]string @@ -59,11 +59,11 @@ type T struct { MUI8S map[uint8]string SMSI []map[string]int // Empty interfaces; used to see if we can dig inside one. - Empty0 interface{} // nil - Empty1 interface{} - Empty2 interface{} - Empty3 interface{} - Empty4 interface{} + Empty0 any // nil + Empty1 any + Empty2 any + Empty3 any + Empty4 any // Non-empty interfaces. NonEmptyInterface I NonEmptyInterfacePtS *I @@ -141,7 +141,7 @@ var tVal = &T{ SB: []bool{true, false}, MSI: map[string]int{"one": 1, "two": 2, "three": 3}, MSIone: map[string]int{"one": 1}, - MXI: map[interface{}]int{"one": 1}, + MXI: map[any]int{"one": 1}, MII: map[int]int{1: 1}, MI32S: map[int32]string{1: "one", 2: "two"}, MI64S: map[int64]string{2: "i642", 3: "i643"}, @@ -212,7 +212,7 @@ func (t *T) Method2(a uint16, b string) string { return fmt.Sprintf("Method2: %d %s", a, b) } -func (t *T) Method3(v interface{}) string { +func (t *T) Method3(v any) string { return fmt.Sprintf("Method3: %v", v) } @@ -252,7 +252,7 @@ func (u *U) TrueFalse(b bool) string { return "" } -func typeOf(arg interface{}) string { +func typeOf(arg any) string { return fmt.Sprintf("%T", arg) } @@ -260,7 +260,7 @@ type execTest struct { name string input string output string - data interface{} + data any ok bool } @@ -393,7 +393,7 @@ var execTests = []execTest{ {".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=<he+llo>", tVal, true}, {"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true}, {"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true}, - {"Interface Call", `{{stringer .S}}`, "foozle", map[string]interface{}{"S": bytes.NewBufferString("foozle")}, true}, + {"Interface Call", `{{stringer .S}}`, "foozle", map[string]any{"S": bytes.NewBufferString("foozle")}, true}, {".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true}, {"call nil", "{{call nil}}", "", tVal, false}, @@ -740,7 +740,7 @@ func add(args ...int) int { return sum } -func echo(arg interface{}) interface{} { +func echo(arg any) any { return arg } @@ -759,7 +759,7 @@ func stringer(s fmt.Stringer) string { return s.String() } -func mapOfThree() interface{} { +func mapOfThree() any { return map[string]int{"three": 3} } @@ -1438,7 +1438,7 @@ func TestBlock(t *testing.T) { func TestEvalFieldErrors(t *testing.T) { tests := []struct { name, src string - value interface{} + value any want string }{ { @@ -1581,7 +1581,7 @@ func TestInterfaceValues(t *testing.T) { for _, tt := range tests { tmpl := Must(New("tmpl").Parse(tt.text)) var buf bytes.Buffer - err := tmpl.Execute(&buf, map[string]interface{}{ + err := tmpl.Execute(&buf, map[string]any{ "PlusOne": func(n int) int { return n + 1 }, @@ -1610,7 +1610,7 @@ func TestInterfaceValues(t *testing.T) { // Check that panics during calls are recovered and returned as errors. func TestExecutePanicDuringCall(t *testing.T) { - funcs := map[string]interface{}{ + funcs := map[string]any{ "doPanic": func() string { panic("custom panic string") }, @@ -1618,7 +1618,7 @@ func TestExecutePanicDuringCall(t *testing.T) { tests := []struct { name string input string - data interface{} + data any wantErr string }{ { @@ -1816,7 +1816,7 @@ func TestRecursiveExecuteViaMethod(t *testing.T) { func TestTemplateFuncsAfterClone(t *testing.T) { s := `{{ f . }}` want := "test" - orig := New("orig").Funcs(map[string]interface{}{ + orig := New("orig").Funcs(map[string]any{ "f": func(in string) string { return in }, diff --git a/src/html/template/html.go b/src/html/template/html.go index 356b8298ae36d..19bd0ccb204b1 100644 --- a/src/html/template/html.go +++ b/src/html/template/html.go @@ -12,7 +12,7 @@ import ( ) // htmlNospaceEscaper escapes for inclusion in unquoted attribute values. -func htmlNospaceEscaper(args ...interface{}) string { +func htmlNospaceEscaper(args ...any) string { s, t := stringify(args...) if t == contentTypeHTML { return htmlReplacer(stripTags(s), htmlNospaceNormReplacementTable, false) @@ -21,7 +21,7 @@ func htmlNospaceEscaper(args ...interface{}) string { } // attrEscaper escapes for inclusion in quoted attribute values. -func attrEscaper(args ...interface{}) string { +func attrEscaper(args ...any) string { s, t := stringify(args...) if t == contentTypeHTML { return htmlReplacer(stripTags(s), htmlNormReplacementTable, true) @@ -30,7 +30,7 @@ func attrEscaper(args ...interface{}) string { } // rcdataEscaper escapes for inclusion in an RCDATA element body. -func rcdataEscaper(args ...interface{}) string { +func rcdataEscaper(args ...any) string { s, t := stringify(args...) if t == contentTypeHTML { return htmlReplacer(s, htmlNormReplacementTable, true) @@ -39,7 +39,7 @@ func rcdataEscaper(args ...interface{}) string { } // htmlEscaper escapes for inclusion in HTML text. -func htmlEscaper(args ...interface{}) string { +func htmlEscaper(args ...any) string { s, t := stringify(args...) if t == contentTypeHTML { return s @@ -225,7 +225,7 @@ func stripTags(html string) string { // htmlNameFilter accepts valid parts of an HTML attribute or tag name or // a known-safe HTML attribute. -func htmlNameFilter(args ...interface{}) string { +func htmlNameFilter(args ...any) string { s, t := stringify(args...) if t == contentTypeHTMLAttr { return s @@ -260,6 +260,6 @@ func htmlNameFilter(args ...interface{}) string { // content interpolated into comments. // This approach is equally valid whether or not static comment content is // removed from the template. -func commentEscaper(args ...interface{}) string { +func commentEscaper(args ...any) string { return "" } diff --git a/src/html/template/js.go b/src/html/template/js.go index 7e919c48e6f67..50523d00f167f 100644 --- a/src/html/template/js.go +++ b/src/html/template/js.go @@ -122,7 +122,7 @@ var jsonMarshalType = reflect.TypeOf((*json.Marshaler)(nil)).Elem() // indirectToJSONMarshaler returns the value, after dereferencing as many times // as necessary to reach the base type (or nil) or an implementation of json.Marshal. -func indirectToJSONMarshaler(a interface{}) interface{} { +func indirectToJSONMarshaler(a any) any { // text/template now supports passing untyped nil as a func call // argument, so we must support it. Otherwise we'd panic below, as one // cannot call the Type or Interface methods on an invalid @@ -140,8 +140,8 @@ func indirectToJSONMarshaler(a interface{}) interface{} { // jsValEscaper escapes its inputs to a JS Expression (section 11.14) that has // neither side-effects nor free variables outside (NaN, Infinity). -func jsValEscaper(args ...interface{}) string { - var a interface{} +func jsValEscaper(args ...any) string { + var a any if len(args) == 1 { a = indirectToJSONMarshaler(args[0]) switch t := a.(type) { @@ -224,7 +224,7 @@ func jsValEscaper(args ...interface{}) string { // jsStrEscaper produces a string that can be included between quotes in // JavaScript source, in JavaScript embedded in an HTML5 ", "-->"}, `["\u003c!--","\u003c/script\u003e","--\u003e"]`}, {"", `"--\u003e"`}, @@ -158,7 +158,7 @@ func TestJSValEscaper(t *testing.T) { } // Make sure that escaping corner cases are not broken // by nesting. - a := []interface{}{test.x} + a := []any{test.x} want := "[" + strings.TrimSpace(test.js) + "]" if js := jsValEscaper(a); js != want { t.Errorf("%+v: want\n\t%q\ngot\n\t%q", a, want, js) @@ -168,7 +168,7 @@ func TestJSValEscaper(t *testing.T) { func TestJSStrEscaper(t *testing.T) { tests := []struct { - x interface{} + x any esc string }{ {"", ``}, @@ -223,7 +223,7 @@ func TestJSStrEscaper(t *testing.T) { func TestJSRegexpEscaper(t *testing.T) { tests := []struct { - x interface{} + x any esc string }{ {"", `(?:)`}, @@ -278,7 +278,7 @@ func TestEscapersOnLower7AndSelectHighCodepoints(t *testing.T) { tests := []struct { name string - escaper func(...interface{}) string + escaper func(...any) string escaped string }{ { diff --git a/src/html/template/template.go b/src/html/template/template.go index 69312d36fdb36..7eba716f1b664 100644 --- a/src/html/template/template.go +++ b/src/html/template/template.go @@ -117,7 +117,7 @@ func (t *Template) escape() error { // the output writer. // A template may be executed safely in parallel, although if parallel // executions share a Writer the output may be interleaved. -func (t *Template) Execute(wr io.Writer, data interface{}) error { +func (t *Template) Execute(wr io.Writer, data any) error { if err := t.escape(); err != nil { return err } @@ -131,7 +131,7 @@ func (t *Template) Execute(wr io.Writer, data interface{}) error { // the output writer. // A template may be executed safely in parallel, although if parallel // executions share a Writer the output may be interleaved. -func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error { +func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error { tmpl, err := t.lookupAndEscapeTemplate(name) if err != nil { return err @@ -335,7 +335,7 @@ func (t *Template) Name() string { // terminates and Execute returns that error. FuncMap has the same base type // as FuncMap in "text/template", copied here so clients need not import // "text/template". -type FuncMap map[string]interface{} +type FuncMap map[string]any // Funcs adds the elements of the argument map to the template's function map. // It must be called before the template is parsed. @@ -486,7 +486,7 @@ func parseGlob(t *Template, pattern string) (*Template, error) { // IsTrue reports whether the value is 'true', in the sense of not the zero of its type, // and whether the value has a meaningful truth value. This is the definition of // truth used by if and other such actions. -func IsTrue(val interface{}) (truth, ok bool) { +func IsTrue(val any) (truth, ok bool) { return template.IsTrue(val) } diff --git a/src/html/template/template_test.go b/src/html/template/template_test.go index 1f2c888bbea9d..99a1091c77107 100644 --- a/src/html/template/template_test.go +++ b/src/html/template/template_test.go @@ -206,7 +206,7 @@ func (c *testCase) mustNotParse(t *Template, text string) { } } -func (c *testCase) mustExecute(t *Template, val interface{}, want string) { +func (c *testCase) mustExecute(t *Template, val any, want string) { var buf bytes.Buffer err := t.Execute(&buf, val) if err != nil { diff --git a/src/html/template/url.go b/src/html/template/url.go index 4b39fddf07df4..93905586a2f41 100644 --- a/src/html/template/url.go +++ b/src/html/template/url.go @@ -32,7 +32,7 @@ import ( // To allow URLs containing other schemes to bypass this filter, developers must // explicitly indicate that such a URL is expected and safe by encapsulating it // in a template.URL value. -func urlFilter(args ...interface{}) string { +func urlFilter(args ...any) string { s, t := stringify(args...) if t == contentTypeURL { return s @@ -56,7 +56,7 @@ func isSafeURL(s string) bool { // urlEscaper produces an output that can be embedded in a URL query. // The output can be embedded in an HTML attribute without further escaping. -func urlEscaper(args ...interface{}) string { +func urlEscaper(args ...any) string { return urlProcessor(false, args...) } @@ -65,13 +65,13 @@ func urlEscaper(args ...interface{}) string { // The normalizer does not encode all HTML specials. Specifically, it does not // encode '&' so correct embedding in an HTML attribute requires escaping of // '&' to '&'. -func urlNormalizer(args ...interface{}) string { +func urlNormalizer(args ...any) string { return urlProcessor(true, args...) } // urlProcessor normalizes (when norm is true) or escapes its input to produce // a valid hierarchical or opaque URL part. -func urlProcessor(norm bool, args ...interface{}) string { +func urlProcessor(norm bool, args ...any) string { s, t := stringify(args...) if t == contentTypeURL { norm = true @@ -141,7 +141,7 @@ func processURLOnto(s string, norm bool, b *bytes.Buffer) bool { // Filters and normalizes srcset values which are comma separated // URLs followed by metadata. -func srcsetFilterAndEscaper(args ...interface{}) string { +func srcsetFilterAndEscaper(args ...any) string { s, t := stringify(args...) switch t { case contentTypeSrcset: diff --git a/src/html/template/url_test.go b/src/html/template/url_test.go index 75c354eba87de..a04f39cdff530 100644 --- a/src/html/template/url_test.go +++ b/src/html/template/url_test.go @@ -48,7 +48,7 @@ func TestURLFilters(t *testing.T) { tests := []struct { name string - escaper func(...interface{}) string + escaper func(...any) string escaped string }{ { diff --git a/src/image/draw/draw_test.go b/src/image/draw/draw_test.go index 77f1c5c2c2cfb..3be93962ad738 100644 --- a/src/image/draw/draw_test.go +++ b/src/image/draw/draw_test.go @@ -84,7 +84,7 @@ func convertToSlowestRGBA(m image.Image) *slowestRGBA { } func init() { - var p interface{} = (*slowestRGBA)(nil) + var p any = (*slowestRGBA)(nil) if _, ok := p.(RGBA64Image); ok { panic("slowestRGBA should not be an RGBA64Image") } @@ -173,7 +173,7 @@ func convertToSlowerRGBA(m image.Image) *slowerRGBA { } func init() { - var p interface{} = (*slowerRGBA)(nil) + var p any = (*slowerRGBA)(nil) if _, ok := p.(RGBA64Image); !ok { panic("slowerRGBA should be an RGBA64Image") } diff --git a/src/internal/abi/abi.go b/src/internal/abi/abi.go index b266a7ff78201..11acac346fbbc 100644 --- a/src/internal/abi/abi.go +++ b/src/internal/abi/abi.go @@ -114,7 +114,7 @@ func (b *IntArgRegBitmap) Get(i int) bool { // compile-time error. // // Implemented as a compile intrinsic. -func FuncPCABI0(f interface{}) uintptr +func FuncPCABI0(f any) uintptr // FuncPCABIInternal returns the entry PC of the function f. If f is a // direct reference of a function, it must be defined as ABIInternal. @@ -123,4 +123,4 @@ func FuncPCABI0(f interface{}) uintptr // the behavior is undefined. // // Implemented as a compile intrinsic. -func FuncPCABIInternal(f interface{}) uintptr +func FuncPCABIInternal(f any) uintptr diff --git a/src/internal/fmtsort/sort_test.go b/src/internal/fmtsort/sort_test.go index ab063af5bae66..11befca6f1921 100644 --- a/src/internal/fmtsort/sort_test.go +++ b/src/internal/fmtsort/sort_test.go @@ -38,12 +38,12 @@ var compareTests = [][]reflect.Value{ ct(reflect.TypeOf(chans[0]), chans[0], chans[1], chans[2]), ct(reflect.TypeOf(toy{}), toy{0, 1}, toy{0, 2}, toy{1, -1}, toy{1, 1}), ct(reflect.TypeOf([2]int{}), [2]int{1, 1}, [2]int{1, 2}, [2]int{2, 0}), - ct(reflect.TypeOf(interface{}(interface{}(0))), iFace, 1, 2, 3), + ct(reflect.TypeOf(any(any(0))), iFace, 1, 2, 3), } -var iFace interface{} +var iFace any -func ct(typ reflect.Type, args ...interface{}) []reflect.Value { +func ct(typ reflect.Type, args ...any) []reflect.Value { value := make([]reflect.Value, len(args)) for i, v := range args { x := reflect.ValueOf(v) @@ -84,8 +84,8 @@ func TestCompare(t *testing.T) { } type sortTest struct { - data interface{} // Always a map. - print string // Printed result using our custom printer. + data any // Always a map. + print string // Printed result using our custom printer. } var sortTests = []sortTest{ @@ -135,7 +135,7 @@ var sortTests = []sortTest{ }, } -func sprint(data interface{}) string { +func sprint(data any) string { om := fmtsort.Sort(reflect.ValueOf(data)) if om == nil { return "nil" @@ -244,7 +244,7 @@ func TestInterface(t *testing.T) { // A map containing multiple concrete types should be sorted by type, // then value. However, the relative ordering of types is unspecified, // so test this by checking the presence of sorted subgroups. - m := map[interface{}]string{ + m := map[any]string{ [2]int{1, 0}: "", [2]int{0, 1}: "", true: "", diff --git a/src/internal/fuzz/encoding.go b/src/internal/fuzz/encoding.go index d3f24c3e6c8db..2bfa02b8c06d9 100644 --- a/src/internal/fuzz/encoding.go +++ b/src/internal/fuzz/encoding.go @@ -18,7 +18,7 @@ var encVersion1 = "go test fuzz v1" // marshalCorpusFile encodes an arbitrary number of arguments into the file format for the // corpus. -func marshalCorpusFile(vals ...interface{}) []byte { +func marshalCorpusFile(vals ...any) []byte { if len(vals) == 0 { panic("must have at least one value to marshal") } @@ -45,7 +45,7 @@ func marshalCorpusFile(vals ...interface{}) []byte { } // unmarshalCorpusFile decodes corpus bytes into their respective values. -func unmarshalCorpusFile(b []byte) ([]interface{}, error) { +func unmarshalCorpusFile(b []byte) ([]any, error) { if len(b) == 0 { return nil, fmt.Errorf("cannot unmarshal empty string") } @@ -56,7 +56,7 @@ func unmarshalCorpusFile(b []byte) ([]interface{}, error) { if string(lines[0]) != encVersion1 { return nil, fmt.Errorf("unknown encoding version: %s", lines[0]) } - var vals []interface{} + var vals []any for _, line := range lines[1:] { line = bytes.TrimSpace(line) if len(line) == 0 { @@ -71,7 +71,7 @@ func unmarshalCorpusFile(b []byte) ([]interface{}, error) { return vals, nil } -func parseCorpusValue(line []byte) (interface{}, error) { +func parseCorpusValue(line []byte) (any, error) { fs := token.NewFileSet() expr, err := parser.ParseExprFrom(fs, "(test)", line, 0) if err != nil { @@ -197,7 +197,7 @@ func parseCorpusValue(line []byte) (interface{}, error) { } // parseInt returns an integer of value val and type typ. -func parseInt(val, typ string) (interface{}, error) { +func parseInt(val, typ string) (any, error) { switch typ { case "int": return strconv.Atoi(val) @@ -218,7 +218,7 @@ func parseInt(val, typ string) (interface{}, error) { } // parseInt returns an unsigned integer of value val and type typ. -func parseUint(val, typ string) (interface{}, error) { +func parseUint(val, typ string) (any, error) { switch typ { case "uint": i, err := strconv.ParseUint(val, 10, 0) diff --git a/src/internal/fuzz/fuzz.go b/src/internal/fuzz/fuzz.go index cb739232c7ae0..b3f1381dbbf58 100644 --- a/src/internal/fuzz/fuzz.go +++ b/src/internal/fuzz/fuzz.go @@ -455,7 +455,7 @@ type CorpusEntry = struct { Data []byte // Values is the unmarshaled values from a corpus file. - Values []interface{} + Values []any Generation int @@ -684,7 +684,7 @@ func newCoordinator(opts CoordinateFuzzingOpts) (*coordinator, error) { if len(c.corpus.entries) == 0 { fmt.Fprintf(c.opts.Log, "warning: starting with empty corpus\n") - var vals []interface{} + var vals []any for _, t := range opts.Types { vals = append(vals, zeroValue(t)) } @@ -968,7 +968,7 @@ func ReadCorpus(dir string, types []reflect.Type) ([]CorpusEntry, error) { if err != nil { return nil, fmt.Errorf("failed to read corpus file: %v", err) } - var vals []interface{} + var vals []any vals, err = readCorpusData(data, types) if err != nil { errs = append(errs, fmt.Errorf("%q: %v", filename, err)) @@ -982,7 +982,7 @@ func ReadCorpus(dir string, types []reflect.Type) ([]CorpusEntry, error) { return corpus, nil } -func readCorpusData(data []byte, types []reflect.Type) ([]interface{}, error) { +func readCorpusData(data []byte, types []reflect.Type) ([]any, error) { vals, err := unmarshalCorpusFile(data) if err != nil { return nil, fmt.Errorf("unmarshal: %v", err) @@ -995,7 +995,7 @@ func readCorpusData(data []byte, types []reflect.Type) ([]interface{}, error) { // CheckCorpus verifies that the types in vals match the expected types // provided. -func CheckCorpus(vals []interface{}, types []reflect.Type) error { +func CheckCorpus(vals []any, types []reflect.Type) error { if len(vals) != len(types) { return fmt.Errorf("wrong number of values in corpus entry: %d, want %d", len(vals), len(types)) } @@ -1032,7 +1032,7 @@ func testName(path string) string { return filepath.Base(path) } -func zeroValue(t reflect.Type) interface{} { +func zeroValue(t reflect.Type) any { for _, v := range zeroVals { if reflect.TypeOf(v) == t { return v @@ -1041,7 +1041,7 @@ func zeroValue(t reflect.Type) interface{} { panic(fmt.Sprintf("unsupported type: %v", t)) } -var zeroVals []interface{} = []interface{}{ +var zeroVals []any = []any{ []byte(""), string(""), false, diff --git a/src/internal/fuzz/minimize_test.go b/src/internal/fuzz/minimize_test.go index f9041d1d34510..6e5f3184b4e06 100644 --- a/src/internal/fuzz/minimize_test.go +++ b/src/internal/fuzz/minimize_test.go @@ -22,8 +22,8 @@ func TestMinimizeInput(t *testing.T) { type testcase struct { name string fn func(CorpusEntry) error - input []interface{} - expected []interface{} + input []any + expected []any } cases := []testcase{ { @@ -41,8 +41,8 @@ func TestMinimizeInput(t *testing.T) { } return nil }, - input: []interface{}{[]byte{0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, - expected: []interface{}{[]byte{1, 1, 1}}, + input: []any{[]byte{0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + expected: []any{[]byte{1, 1, 1}}, }, { name: "single_bytes", @@ -56,8 +56,8 @@ func TestMinimizeInput(t *testing.T) { } return fmt.Errorf("bad %v", e.Values[0]) }, - input: []interface{}{[]byte{1, 2, 3, 4, 5}}, - expected: []interface{}{[]byte("00")}, + input: []any{[]byte{1, 2, 3, 4, 5}}, + expected: []any{[]byte("00")}, }, { name: "set_of_bytes", @@ -71,8 +71,8 @@ func TestMinimizeInput(t *testing.T) { } return nil }, - input: []interface{}{[]byte{0, 1, 2, 3, 4, 5}}, - expected: []interface{}{[]byte{0, 4, 5}}, + input: []any{[]byte{0, 1, 2, 3, 4, 5}}, + expected: []any{[]byte{0, 4, 5}}, }, { name: "non_ascii_bytes", @@ -83,8 +83,8 @@ func TestMinimizeInput(t *testing.T) { } return nil }, - input: []interface{}{[]byte("ท")}, // ท is 3 bytes - expected: []interface{}{[]byte("000")}, + input: []any{[]byte("ท")}, // ท is 3 bytes + expected: []any{[]byte("000")}, }, { name: "ones_string", @@ -101,8 +101,8 @@ func TestMinimizeInput(t *testing.T) { } return nil }, - input: []interface{}{"001010001000000000000000000"}, - expected: []interface{}{"111"}, + input: []any{"001010001000000000000000000"}, + expected: []any{"111"}, }, { name: "string_length", @@ -113,8 +113,8 @@ func TestMinimizeInput(t *testing.T) { } return nil }, - input: []interface{}{"zzzzz"}, - expected: []interface{}{"00000"}, + input: []any{"zzzzz"}, + expected: []any{"00000"}, }, { name: "string_with_letter", @@ -126,8 +126,8 @@ func TestMinimizeInput(t *testing.T) { } return nil }, - input: []interface{}{"ZZZZZ"}, - expected: []interface{}{"A"}, + input: []any{"ZZZZZ"}, + expected: []any{"A"}, }, } @@ -167,7 +167,7 @@ func TestMinimizeFlaky(t *testing.T) { return time.Second, errors.New("ohno") }} mem := &sharedMem{region: make([]byte, 100)} // big enough to hold value and header - vals := []interface{}{[]byte(nil)} + vals := []any{[]byte(nil)} args := minimizeArgs{KeepCoverage: make([]byte, len(coverageSnapshot))} success, err := ws.minimizeInput(context.Background(), vals, mem, args) if success { diff --git a/src/internal/fuzz/mutator.go b/src/internal/fuzz/mutator.go index a3161c04ea09c..e26ae5a5836c2 100644 --- a/src/internal/fuzz/mutator.go +++ b/src/internal/fuzz/mutator.go @@ -53,7 +53,7 @@ func min(a, b int) int { } // mutate performs several mutations on the provided values. -func (m *mutator) mutate(vals []interface{}, maxBytes int) { +func (m *mutator) mutate(vals []any, maxBytes int) { // TODO(katiehockman): pull some of these functions into helper methods and // test that each case is working as expected. // TODO(katiehockman): perform more types of mutations for []byte. diff --git a/src/internal/fuzz/mutator_test.go b/src/internal/fuzz/mutator_test.go index d8015ce213883..cea7e2e3be8c3 100644 --- a/src/internal/fuzz/mutator_test.go +++ b/src/internal/fuzz/mutator_test.go @@ -34,7 +34,7 @@ func BenchmarkMutatorBytes(b *testing.B) { // resize buffer to the correct shape and reset the PCG buf = buf[0:size] m.r = newPcgRand() - m.mutate([]interface{}{buf}, workerSharedMemSize) + m.mutate([]any{buf}, workerSharedMemSize) } }) } @@ -62,7 +62,7 @@ func BenchmarkMutatorString(b *testing.B) { // resize buffer to the correct shape and reset the PCG buf = buf[0:size] m.r = newPcgRand() - m.mutate([]interface{}{string(buf)}, workerSharedMemSize) + m.mutate([]any{string(buf)}, workerSharedMemSize) } }) } @@ -74,7 +74,7 @@ func BenchmarkMutatorAllBasicTypes(b *testing.B) { os.Setenv("GODEBUG", fmt.Sprintf("%s,fuzzseed=123", origEnv)) m := newMutator() - types := []interface{}{ + types := []any{ []byte(""), string(""), false, @@ -95,14 +95,14 @@ func BenchmarkMutatorAllBasicTypes(b *testing.B) { b.Run(fmt.Sprintf("%T", t), func(b *testing.B) { for i := 0; i < b.N; i++ { m.r = newPcgRand() - m.mutate([]interface{}{t}, workerSharedMemSize) + m.mutate([]any{t}, workerSharedMemSize) } }) } } func TestStringImmutability(t *testing.T) { - v := []interface{}{"hello"} + v := []any{"hello"} m := newMutator() m.mutate(v, 1024) original := v[0].(string) diff --git a/src/internal/fuzz/queue.go b/src/internal/fuzz/queue.go index cf67a28ba727f..42a8379541f88 100644 --- a/src/internal/fuzz/queue.go +++ b/src/internal/fuzz/queue.go @@ -16,7 +16,7 @@ type queue struct { // The queue is empty when begin = end. // The queue is full (until grow is called) when end = begin + N - 1 (mod N) // where N = cap(elems). - elems []interface{} + elems []any head, len int } @@ -30,7 +30,7 @@ func (q *queue) grow() { if newCap == 0 { newCap = 8 } - newElems := make([]interface{}, newCap) + newElems := make([]any, newCap) oldLen := q.len for i := 0; i < oldLen; i++ { newElems[i] = q.elems[(q.head+i)%oldCap] @@ -39,7 +39,7 @@ func (q *queue) grow() { q.head = 0 } -func (q *queue) enqueue(e interface{}) { +func (q *queue) enqueue(e any) { if q.len+1 > q.cap() { q.grow() } @@ -48,7 +48,7 @@ func (q *queue) enqueue(e interface{}) { q.len++ } -func (q *queue) dequeue() (interface{}, bool) { +func (q *queue) dequeue() (any, bool) { if q.len == 0 { return nil, false } @@ -59,7 +59,7 @@ func (q *queue) dequeue() (interface{}, bool) { return e, true } -func (q *queue) peek() (interface{}, bool) { +func (q *queue) peek() (any, bool) { if q.len == 0 { return nil, false } diff --git a/src/internal/fuzz/worker.go b/src/internal/fuzz/worker.go index c39804cad177f..c2d553240c838 100644 --- a/src/internal/fuzz/worker.go +++ b/src/internal/fuzz/worker.go @@ -654,7 +654,7 @@ func (ws *workerServer) serve(ctx context.Context) error { } } - var resp interface{} + var resp any switch { case c.Fuzz != nil: resp = ws.fuzz(ctx, *c.Fuzz) @@ -726,7 +726,7 @@ func (ws *workerServer) fuzz(ctx context.Context, args fuzzArgs) (resp fuzzRespo resp.InternalErr = err.Error() return resp } - vals := make([]interface{}, len(originalVals)) + vals := make([]any, len(originalVals)) copy(vals, originalVals) shouldStop := func() bool { @@ -827,7 +827,7 @@ func (ws *workerServer) minimize(ctx context.Context, args minimizeArgs) (resp m // coverage, in fuzzFn. It uses the context to determine how long to run, // stopping once closed. It returns a bool indicating whether minimization was // successful and an error if one was found. -func (ws *workerServer) minimizeInput(ctx context.Context, vals []interface{}, mem *sharedMem, args minimizeArgs) (success bool, retErr error) { +func (ws *workerServer) minimizeInput(ctx context.Context, vals []any, mem *sharedMem, args minimizeArgs) (success bool, retErr error) { keepCoverage := args.KeepCoverage memBytes := mem.valueRef() bPtr := &memBytes @@ -900,7 +900,7 @@ func (ws *workerServer) minimizeInput(ctx context.Context, vals []interface{}, m return true, retErr } -func writeToMem(vals []interface{}, mem *sharedMem) { +func writeToMem(vals []any, mem *sharedMem) { b := marshalCorpusFile(vals...) mem.setValue(b) } @@ -1127,7 +1127,7 @@ func (wc *workerClient) ping(ctx context.Context) error { // callLocked sends an RPC from the coordinator to the worker process and waits // for the response. The callLocked may be cancelled with ctx. -func (wc *workerClient) callLocked(ctx context.Context, c call, resp interface{}) (err error) { +func (wc *workerClient) callLocked(ctx context.Context, c call, resp any) (err error) { enc := json.NewEncoder(wc.fuzzIn) dec := json.NewDecoder(&contextReader{ctx: ctx, r: wc.fuzzOut}) if err := enc.Encode(c); err != nil { diff --git a/src/internal/fuzz/worker_test.go b/src/internal/fuzz/worker_test.go index e2ecf0a9c3ab5..d0b21da783864 100644 --- a/src/internal/fuzz/worker_test.go +++ b/src/internal/fuzz/worker_test.go @@ -53,7 +53,7 @@ func BenchmarkWorkerFuzzOverhead(b *testing.B) { } }() - initialVal := []interface{}{make([]byte, 32)} + initialVal := []any{make([]byte, 32)} encodedVals := marshalCorpusFile(initialVal...) mem.setValue(encodedVals) @@ -92,7 +92,7 @@ func BenchmarkWorkerFuzz(b *testing.B) { } b.SetParallelism(1) w := newWorkerForTest(b) - entry := CorpusEntry{Values: []interface{}{[]byte(nil)}} + entry := CorpusEntry{Values: []any{[]byte(nil)}} entry.Data = marshalCorpusFile(entry.Values...) for i := int64(0); i < int64(b.N); { args := fuzzArgs{ @@ -183,7 +183,7 @@ func BenchmarkWorkerMinimize(b *testing.B) { ctx := context.Background() for sz := 1; sz <= len(bytes); sz <<= 1 { sz := sz - input := []interface{}{bytes[:sz]} + input := []any{bytes[:sz]} encodedVals := marshalCorpusFile(input...) mem = <-ws.memMu mem.setValue(encodedVals) diff --git a/src/internal/intern/intern.go b/src/internal/intern/intern.go index 666caa6d2f6a6..75641106abdf9 100644 --- a/src/internal/intern/intern.go +++ b/src/internal/intern/intern.go @@ -21,7 +21,7 @@ import ( // See func Get for how Value pointers may be used. type Value struct { _ [0]func() // prevent people from accidentally using value type as comparable - cmpVal interface{} + cmpVal any // resurrected is guarded by mu (for all instances of Value). // It is set true whenever v is synthesized from a uintptr. resurrected bool @@ -29,21 +29,21 @@ type Value struct { // Get returns the comparable value passed to the Get func // that returned v. -func (v *Value) Get() interface{} { return v.cmpVal } +func (v *Value) Get() any { return v.cmpVal } // key is a key in our global value map. // It contains type-specialized fields to avoid allocations // when converting common types to empty interfaces. type key struct { s string - cmpVal interface{} + cmpVal any // isString reports whether key contains a string. // Without it, the zero value of key is ambiguous. isString bool } // keyFor returns a key to use with cmpVal. -func keyFor(cmpVal interface{}) key { +func keyFor(cmpVal any) key { if s, ok := cmpVal.(string); ok { return key{s: s, isString: true} } @@ -79,7 +79,7 @@ func safeMap() map[key]*Value { // // The returned pointer will be the same for Get(v) and Get(v2) // if and only if v == v2, and can be used as a map key. -func Get(cmpVal interface{}) *Value { +func Get(cmpVal any) *Value { return get(keyFor(cmpVal)) } diff --git a/src/internal/lazytemplate/lazytemplate.go b/src/internal/lazytemplate/lazytemplate.go index c83eaeaf3ec6e..8eeed5a527ac6 100644 --- a/src/internal/lazytemplate/lazytemplate.go +++ b/src/internal/lazytemplate/lazytemplate.go @@ -33,7 +33,7 @@ func (r *Template) build() { r.name, r.text = "", "" } -func (r *Template) Execute(w io.Writer, data interface{}) error { +func (r *Template) Execute(w io.Writer, data any) error { return r.tp().Execute(w, data) } diff --git a/src/internal/nettrace/nettrace.go b/src/internal/nettrace/nettrace.go index de3254df589f0..94f38a71eeb70 100644 --- a/src/internal/nettrace/nettrace.go +++ b/src/internal/nettrace/nettrace.go @@ -30,7 +30,7 @@ type Trace struct { // The coalesced parameter is whether singleflight de-dupped // the call. The addrs are of type net.IPAddr but can't // actually be for circular dependency reasons. - DNSDone func(netIPs []interface{}, coalesced bool, err error) + DNSDone func(netIPs []any, coalesced bool, err error) // ConnectStart is called before a Dial, excluding Dials made // during DNS lookups. In the case of DualStack (Happy Eyeballs) diff --git a/src/internal/poll/splice_linux.go b/src/internal/poll/splice_linux.go index 2d87c3d023b14..43eec04a71485 100644 --- a/src/internal/poll/splice_linux.go +++ b/src/internal/poll/splice_linux.go @@ -173,7 +173,7 @@ type splicePipe struct { // a finalizer for each pipe to close its file descriptors before the actual GC. var splicePipePool = sync.Pool{New: newPoolPipe} -func newPoolPipe() interface{} { +func newPoolPipe() any { // Discard the error which occurred during the creation of pipe buffer, // redirecting the data transmission to the conventional way utilizing read() + write() as a fallback. p := newPipe() diff --git a/src/internal/poll/splice_linux_test.go b/src/internal/poll/splice_linux_test.go index 8c4363886e7e3..29bcaab4140f7 100644 --- a/src/internal/poll/splice_linux_test.go +++ b/src/internal/poll/splice_linux_test.go @@ -73,7 +73,7 @@ func TestSplicePipePool(t *testing.T) { // Detect whether all pipes are closed properly. var leakedFDs []int - pendingFDs.Range(func(k, v interface{}) bool { + pendingFDs.Range(func(k, v any) bool { leakedFDs = append(leakedFDs, k.(int)) return true }) diff --git a/src/internal/reflectlite/all_test.go b/src/internal/reflectlite/all_test.go index e15f364fcd33f..ea750831efbe5 100644 --- a/src/internal/reflectlite/all_test.go +++ b/src/internal/reflectlite/all_test.go @@ -32,7 +32,7 @@ type T struct { } type pair struct { - i interface{} + i any s string } @@ -421,7 +421,7 @@ func TestAll(t *testing.T) { func TestInterfaceValue(t *testing.T) { var inter struct { - E interface{} + E any } inter.E = 123.456 v1 := ValueOf(&inter) @@ -437,7 +437,7 @@ func TestInterfaceValue(t *testing.T) { } func TestFunctionValue(t *testing.T) { - var x interface{} = func() {} + var x any = func() {} v := ValueOf(x) if fmt.Sprint(ToInterface(v)) != fmt.Sprint(x) { t.Fatalf("TestFunction returned wrong pointer") @@ -496,7 +496,7 @@ type Basic struct { type NotBasic Basic type DeepEqualTest struct { - a, b interface{} + a, b any eq bool } @@ -510,7 +510,7 @@ var ( type self struct{} type Loop *Loop -type Loopy interface{} +type Loopy any var loop1, loop2 Loop var loopy1, loopy2 Loopy @@ -578,7 +578,7 @@ var typeOfTests = []DeepEqualTest{ {int32(1), int64(1), false}, {0.5, "hello", false}, {[]int{1, 2, 3}, [3]int{1, 2, 3}, false}, - {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false}, + {&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false}, {Basic{1, 0.5}, NotBasic{1, 0.5}, false}, {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false}, @@ -606,14 +606,14 @@ func TestTypeOf(t *testing.T) { } } -func Nil(a interface{}, t *testing.T) { +func Nil(a any, t *testing.T) { n := Field(ValueOf(a), 0) if !n.IsNil() { t.Errorf("%v should be nil", a) } } -func NotNil(a interface{}, t *testing.T) { +func NotNil(a any, t *testing.T) { n := Field(ValueOf(a), 0) if n.IsNil() { t.Errorf("value of type %v should not be nil", TypeString(ValueOf(a).Type())) @@ -623,9 +623,9 @@ func NotNil(a interface{}, t *testing.T) { func TestIsNil(t *testing.T) { // These implement IsNil. // Wrap in extra struct to hide interface type. - doNil := []interface{}{ + doNil := []any{ struct{ x *int }{}, - struct{ x interface{} }{}, + struct{ x any }{}, struct{ x map[string]int }{}, struct{ x func() bool }{}, struct{ x chan int }{}, @@ -668,7 +668,7 @@ func TestIsNil(t *testing.T) { NotNil(mi, t) var ii struct { - x interface{} + x any } Nil(ii, t) ii.x = 2 @@ -770,7 +770,7 @@ func TestImportPath(t *testing.T) { {TypeOf([]byte(nil)), ""}, {TypeOf([]rune(nil)), ""}, {TypeOf(string("")), ""}, - {TypeOf((*interface{})(nil)).Elem(), ""}, + {TypeOf((*any)(nil)).Elem(), ""}, {TypeOf((*byte)(nil)), ""}, {TypeOf((*rune)(nil)), ""}, {TypeOf((*int64)(nil)), ""}, @@ -805,7 +805,7 @@ func noAlloc(t *testing.T, n int, f func(int)) { func TestAllocations(t *testing.T) { noAlloc(t, 100, func(j int) { - var i interface{} + var i any var v Value // We can uncomment this when compiler escape analysis @@ -939,7 +939,7 @@ func TestBigZero(t *testing.T) { func TestInvalid(t *testing.T) { // Used to have inconsistency between IsValid() and Kind() != Invalid. - type T struct{ v interface{} } + type T struct{ v any } v := Field(ValueOf(T{}), 0) if v.IsValid() != true || v.Kind() != Interface { @@ -954,7 +954,7 @@ func TestInvalid(t *testing.T) { type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int type nameTest struct { - v interface{} + v any want string } @@ -966,7 +966,7 @@ var nameTests = []nameTest{ {(*func() D1)(nil), ""}, {(*<-chan D1)(nil), ""}, {(*chan<- D1)(nil), ""}, - {(*interface{})(nil), ""}, + {(*any)(nil), ""}, {(*interface { F() })(nil), ""}, diff --git a/src/internal/reflectlite/export_test.go b/src/internal/reflectlite/export_test.go index 354ea9dbd0732..adae229e92c3c 100644 --- a/src/internal/reflectlite/export_test.go +++ b/src/internal/reflectlite/export_test.go @@ -81,7 +81,7 @@ func Zero(typ Type) Value { // var i interface{} = (v's underlying value) // It panics if the Value was obtained by accessing // unexported struct fields. -func ToInterface(v Value) (i interface{}) { +func ToInterface(v Value) (i any) { return valueInterface(v) } diff --git a/src/internal/reflectlite/set_test.go b/src/internal/reflectlite/set_test.go index a610499d08427..ca7ea9b0bc39d 100644 --- a/src/internal/reflectlite/set_test.go +++ b/src/internal/reflectlite/set_test.go @@ -26,8 +26,8 @@ func TestImplicitSetConversion(t *testing.T) { } var implementsTests = []struct { - x interface{} - t interface{} + x any + t any b bool }{ {new(*bytes.Buffer), new(io.Reader), true}, @@ -73,8 +73,8 @@ func TestImplements(t *testing.T) { } var assignableTests = []struct { - x interface{} - t interface{} + x any + t any b bool }{ {new(chan int), new(<-chan int), true}, @@ -82,13 +82,13 @@ var assignableTests = []struct { {new(*int), new(IntPtr), true}, {new(IntPtr), new(*int), true}, {new(IntPtr), new(IntPtr1), false}, - {new(Ch), new(<-chan interface{}), true}, + {new(Ch), new(<-chan any), true}, // test runs implementsTests too } type IntPtr *int type IntPtr1 *int -type Ch <-chan interface{} +type Ch <-chan any func TestAssignableTo(t *testing.T) { for i, tt := range append(assignableTests, implementsTests...) { diff --git a/src/internal/reflectlite/swapper.go b/src/internal/reflectlite/swapper.go index ac081d49bbbe9..fc402bb38a423 100644 --- a/src/internal/reflectlite/swapper.go +++ b/src/internal/reflectlite/swapper.go @@ -14,7 +14,7 @@ import ( // slice. // // Swapper panics if the provided interface is not a slice. -func Swapper(slice interface{}) func(i, j int) { +func Swapper(slice any) func(i, j int) { v := ValueOf(slice) if v.Kind() != Slice { panic(&ValueError{Method: "Swapper", Kind: v.Kind()}) diff --git a/src/internal/reflectlite/type.go b/src/internal/reflectlite/type.go index fdf1584a272d0..8f649600d21d0 100644 --- a/src/internal/reflectlite/type.go +++ b/src/internal/reflectlite/type.go @@ -707,7 +707,7 @@ func (t *interfaceType) NumMethod() int { return len(t.methods) } // TypeOf returns the reflection Type that represents the dynamic type of i. // If i is a nil interface value, TypeOf returns nil. -func TypeOf(i interface{}) Type { +func TypeOf(i any) Type { eface := *(*emptyInterface)(unsafe.Pointer(&i)) return toType(eface.typ) } diff --git a/src/internal/reflectlite/value.go b/src/internal/reflectlite/value.go index 073406925518a..966230f581701 100644 --- a/src/internal/reflectlite/value.go +++ b/src/internal/reflectlite/value.go @@ -99,9 +99,9 @@ func (v Value) pointer() unsafe.Pointer { } // packEface converts v to the empty interface. -func packEface(v Value) interface{} { +func packEface(v Value) any { t := v.typ - var i interface{} + var i any e := (*emptyInterface)(unsafe.Pointer(&i)) // First, fill in the data portion of the interface. switch { @@ -136,7 +136,7 @@ func packEface(v Value) interface{} { } // unpackEface converts the empty interface i to a Value. -func unpackEface(i interface{}) Value { +func unpackEface(i any) Value { e := (*emptyInterface)(unsafe.Pointer(&i)) // NOTE: don't read e.word until we know whether it is really a pointer or not. t := e.typ @@ -226,11 +226,11 @@ func (v Value) Elem() Value { k := v.kind() switch k { case Interface: - var eface interface{} + var eface any if v.typ.NumMethod() == 0 { - eface = *(*interface{})(v.ptr) + eface = *(*any)(v.ptr) } else { - eface = (interface{})(*(*interface { + eface = (any)(*(*interface { M() })(v.ptr)) } @@ -257,7 +257,7 @@ func (v Value) Elem() Value { panic(&ValueError{"reflectlite.Value.Elem", v.kind()}) } -func valueInterface(v Value) interface{} { +func valueInterface(v Value) any { if v.flag == 0 { panic(&ValueError{"reflectlite.Value.Interface", 0}) } @@ -267,7 +267,7 @@ func valueInterface(v Value) interface{} { // Empty interface has one layout, all interfaces with // methods have a second layout. if v.numMethod() == 0 { - return *(*interface{})(v.ptr) + return *(*any)(v.ptr) } return *(*interface { M() @@ -391,7 +391,7 @@ func unsafe_New(*rtype) unsafe.Pointer // ValueOf returns a new Value initialized to the concrete value // stored in the interface i. ValueOf(nil) returns the zero Value. -func ValueOf(i interface{}) Value { +func ValueOf(i any) Value { if i == nil { return Value{} } @@ -433,7 +433,7 @@ func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value } x := valueInterface(v) if dst.NumMethod() == 0 { - *(*interface{})(target) = x + *(*any)(target) = x } else { ifaceE2I(dst, x, target) } @@ -455,7 +455,7 @@ func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Po return add(p, uintptr(i)*eltSize, "i < len") } -func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer) +func ifaceE2I(t *rtype, src any, dst unsafe.Pointer) // typedmemmove copies a value of type t to dst from src. //go:noescape @@ -464,7 +464,7 @@ func typedmemmove(t *rtype, dst, src unsafe.Pointer) // Dummy annotation marking that the value x escapes, // for use in cases where the reflect code is so clever that // the compiler cannot follow. -func escapes(x interface{}) { +func escapes(x any) { if dummy.b { dummy.x = x } @@ -472,5 +472,5 @@ func escapes(x interface{}) { var dummy struct { b bool - x interface{} + x any } diff --git a/src/internal/singleflight/singleflight.go b/src/internal/singleflight/singleflight.go index b2d82e26c29c6..07b3f40ec03d4 100644 --- a/src/internal/singleflight/singleflight.go +++ b/src/internal/singleflight/singleflight.go @@ -14,7 +14,7 @@ type call struct { // These fields are written once before the WaitGroup is done // and are only read after the WaitGroup is done. - val interface{} + val any err error // These fields are read and written with the singleflight @@ -34,7 +34,7 @@ type Group struct { // Result holds the results of Do, so they can be passed // on a channel. type Result struct { - Val interface{} + Val any Err error Shared bool } @@ -44,7 +44,7 @@ type Result struct { // time. If a duplicate comes in, the duplicate caller waits for the // original to complete and receives the same results. // The return value shared indicates whether v was given to multiple callers. -func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) { +func (g *Group) Do(key string, fn func() (any, error)) (v any, err error, shared bool) { g.mu.Lock() if g.m == nil { g.m = make(map[string]*call) @@ -68,7 +68,7 @@ func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, e // results when they are ready. The second result is true if the function // will eventually be called, false if it will not (because there is // a pending request with this key). -func (g *Group) DoChan(key string, fn func() (interface{}, error)) (<-chan Result, bool) { +func (g *Group) DoChan(key string, fn func() (any, error)) (<-chan Result, bool) { ch := make(chan Result, 1) g.mu.Lock() if g.m == nil { @@ -91,7 +91,7 @@ func (g *Group) DoChan(key string, fn func() (interface{}, error)) (<-chan Resul } // doCall handles the single call for a key. -func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) { +func (g *Group) doCall(c *call, key string, fn func() (any, error)) { c.val, c.err = fn() c.wg.Done() diff --git a/src/internal/singleflight/singleflight_test.go b/src/internal/singleflight/singleflight_test.go index 6404a1775a0de..c2310375f7d73 100644 --- a/src/internal/singleflight/singleflight_test.go +++ b/src/internal/singleflight/singleflight_test.go @@ -15,7 +15,7 @@ import ( func TestDo(t *testing.T) { var g Group - v, err, _ := g.Do("key", func() (interface{}, error) { + v, err, _ := g.Do("key", func() (any, error) { return "bar", nil }) if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want { @@ -29,7 +29,7 @@ func TestDo(t *testing.T) { func TestDoErr(t *testing.T) { var g Group someErr := errors.New("some error") - v, err, _ := g.Do("key", func() (interface{}, error) { + v, err, _ := g.Do("key", func() (any, error) { return nil, someErr }) if err != someErr { @@ -45,7 +45,7 @@ func TestDoDupSuppress(t *testing.T) { var wg1, wg2 sync.WaitGroup c := make(chan string, 1) var calls int32 - fn := func() (interface{}, error) { + fn := func() (any, error) { if atomic.AddInt32(&calls, 1) == 1 { // First invocation. wg1.Done() diff --git a/src/internal/syscall/windows/registry/registry_test.go b/src/internal/syscall/windows/registry/registry_test.go index 134b5450fcace..278b0b491178d 100644 --- a/src/internal/syscall/windows/registry/registry_test.go +++ b/src/internal/syscall/windows/registry/registry_test.go @@ -118,7 +118,7 @@ func equalStringSlice(a, b []string) bool { type ValueTest struct { Type uint32 Name string - Value interface{} + Value any WillFail bool } diff --git a/src/internal/trace/gc.go b/src/internal/trace/gc.go index cc19fdf8912d2..c1bc86234094b 100644 --- a/src/internal/trace/gc.go +++ b/src/internal/trace/gc.go @@ -352,11 +352,11 @@ func (h bandUtilHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *bandUtilHeap) Push(x interface{}) { +func (h *bandUtilHeap) Push(x any) { *h = append(*h, x.(bandUtil)) } -func (h *bandUtilHeap) Pop() interface{} { +func (h *bandUtilHeap) Pop() any { x := (*h)[len(*h)-1] *h = (*h)[:len(*h)-1] return x @@ -386,11 +386,11 @@ func (h utilHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *utilHeap) Push(x interface{}) { +func (h *utilHeap) Push(x any) { *h = append(*h, x.(UtilWindow)) } -func (h *utilHeap) Pop() interface{} { +func (h *utilHeap) Pop() any { x := (*h)[len(*h)-1] *h = (*h)[:len(*h)-1] return x diff --git a/src/internal/unsafeheader/unsafeheader_test.go b/src/internal/unsafeheader/unsafeheader_test.go index 6fb7cca888fa5..f3d1a9bb68882 100644 --- a/src/internal/unsafeheader/unsafeheader_test.go +++ b/src/internal/unsafeheader/unsafeheader_test.go @@ -25,7 +25,7 @@ func TestTypeMatchesReflectType(t *testing.T) { }) } -func testHeaderMatchesReflect(t *testing.T, header, reflectHeader interface{}) { +func testHeaderMatchesReflect(t *testing.T, header, reflectHeader any) { h := reflect.TypeOf(header) rh := reflect.TypeOf(reflectHeader) diff --git a/src/io/fs/fs.go b/src/io/fs/fs.go index e603afadb0b1b..5c0d9a6664869 100644 --- a/src/io/fs/fs.go +++ b/src/io/fs/fs.go @@ -153,7 +153,7 @@ type FileInfo interface { Mode() FileMode // file mode bits ModTime() time.Time // modification time IsDir() bool // abbreviation for Mode().IsDir() - Sys() interface{} // underlying data source (can return nil) + Sys() any // underlying data source (can return nil) } // A FileMode represents a file's mode and permission bits. diff --git a/src/io/io.go b/src/io/io.go index 5635392dfb888..1ea01d5d633df 100644 --- a/src/io/io.go +++ b/src/io/io.go @@ -597,7 +597,7 @@ func (discard) WriteString(s string) (int, error) { } var blackHolePool = sync.Pool{ - New: func() interface{} { + New: func() any { b := make([]byte, 8192) return &b }, diff --git a/src/log/log.go b/src/log/log.go index 3172384718880..5e79b1952241e 100644 --- a/src/log/log.go +++ b/src/log/log.go @@ -198,7 +198,7 @@ func (l *Logger) Output(calldepth int, s string) error { // Printf calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Printf. -func (l *Logger) Printf(format string, v ...interface{}) { +func (l *Logger) Printf(format string, v ...any) { if atomic.LoadInt32(&l.isDiscard) != 0 { return } @@ -207,7 +207,7 @@ func (l *Logger) Printf(format string, v ...interface{}) { // Print calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Print. -func (l *Logger) Print(v ...interface{}) { +func (l *Logger) Print(v ...any) { if atomic.LoadInt32(&l.isDiscard) != 0 { return } @@ -216,7 +216,7 @@ func (l *Logger) Print(v ...interface{}) { // Println calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Println. -func (l *Logger) Println(v ...interface{}) { +func (l *Logger) Println(v ...any) { if atomic.LoadInt32(&l.isDiscard) != 0 { return } @@ -224,39 +224,39 @@ func (l *Logger) Println(v ...interface{}) { } // Fatal is equivalent to l.Print() followed by a call to os.Exit(1). -func (l *Logger) Fatal(v ...interface{}) { +func (l *Logger) Fatal(v ...any) { l.Output(2, fmt.Sprint(v...)) os.Exit(1) } // Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). -func (l *Logger) Fatalf(format string, v ...interface{}) { +func (l *Logger) Fatalf(format string, v ...any) { l.Output(2, fmt.Sprintf(format, v...)) os.Exit(1) } // Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). -func (l *Logger) Fatalln(v ...interface{}) { +func (l *Logger) Fatalln(v ...any) { l.Output(2, fmt.Sprintln(v...)) os.Exit(1) } // Panic is equivalent to l.Print() followed by a call to panic(). -func (l *Logger) Panic(v ...interface{}) { +func (l *Logger) Panic(v ...any) { s := fmt.Sprint(v...) l.Output(2, s) panic(s) } // Panicf is equivalent to l.Printf() followed by a call to panic(). -func (l *Logger) Panicf(format string, v ...interface{}) { +func (l *Logger) Panicf(format string, v ...any) { s := fmt.Sprintf(format, v...) l.Output(2, s) panic(s) } // Panicln is equivalent to l.Println() followed by a call to panic(). -func (l *Logger) Panicln(v ...interface{}) { +func (l *Logger) Panicln(v ...any) { s := fmt.Sprintln(v...) l.Output(2, s) panic(s) @@ -335,7 +335,7 @@ func Writer() io.Writer { // Print calls Output to print to the standard logger. // Arguments are handled in the manner of fmt.Print. -func Print(v ...interface{}) { +func Print(v ...any) { if atomic.LoadInt32(&std.isDiscard) != 0 { return } @@ -344,7 +344,7 @@ func Print(v ...interface{}) { // Printf calls Output to print to the standard logger. // Arguments are handled in the manner of fmt.Printf. -func Printf(format string, v ...interface{}) { +func Printf(format string, v ...any) { if atomic.LoadInt32(&std.isDiscard) != 0 { return } @@ -353,7 +353,7 @@ func Printf(format string, v ...interface{}) { // Println calls Output to print to the standard logger. // Arguments are handled in the manner of fmt.Println. -func Println(v ...interface{}) { +func Println(v ...any) { if atomic.LoadInt32(&std.isDiscard) != 0 { return } @@ -361,39 +361,39 @@ func Println(v ...interface{}) { } // Fatal is equivalent to Print() followed by a call to os.Exit(1). -func Fatal(v ...interface{}) { +func Fatal(v ...any) { std.Output(2, fmt.Sprint(v...)) os.Exit(1) } // Fatalf is equivalent to Printf() followed by a call to os.Exit(1). -func Fatalf(format string, v ...interface{}) { +func Fatalf(format string, v ...any) { std.Output(2, fmt.Sprintf(format, v...)) os.Exit(1) } // Fatalln is equivalent to Println() followed by a call to os.Exit(1). -func Fatalln(v ...interface{}) { +func Fatalln(v ...any) { std.Output(2, fmt.Sprintln(v...)) os.Exit(1) } // Panic is equivalent to Print() followed by a call to panic(). -func Panic(v ...interface{}) { +func Panic(v ...any) { s := fmt.Sprint(v...) std.Output(2, s) panic(s) } // Panicf is equivalent to Printf() followed by a call to panic(). -func Panicf(format string, v ...interface{}) { +func Panicf(format string, v ...any) { s := fmt.Sprintf(format, v...) std.Output(2, s) panic(s) } // Panicln is equivalent to Println() followed by a call to panic(). -func Panicln(v ...interface{}) { +func Panicln(v ...any) { s := fmt.Sprintln(v...) std.Output(2, s) panic(s) diff --git a/src/math/all_test.go b/src/math/all_test.go index 55c805e199ed9..c11d823233148 100644 --- a/src/math/all_test.go +++ b/src/math/all_test.go @@ -3175,7 +3175,7 @@ func TestTrigReduce(t *testing.T) { // https://golang.org/issue/201 type floatTest struct { - val interface{} + val any name string str string } diff --git a/src/math/big/floatconv_test.go b/src/math/big/floatconv_test.go index 3aa68341436fe..a1cc38a4596c5 100644 --- a/src/math/big/floatconv_test.go +++ b/src/math/big/floatconv_test.go @@ -576,7 +576,7 @@ func TestFloatText(t *testing.T) { func TestFloatFormat(t *testing.T) { for _, test := range []struct { format string - value interface{} // float32, float64, or string (== 512bit *Float) + value any // float32, float64, or string (== 512bit *Float) want string }{ // from fmt/fmt_test.go diff --git a/src/math/bits/make_examples.go b/src/math/bits/make_examples.go index ac4004df41490..92e9aabfb5273 100644 --- a/src/math/bits/make_examples.go +++ b/src/math/bits/make_examples.go @@ -37,44 +37,44 @@ func main() { for _, e := range []struct { name string in int - out [4]interface{} - out2 [4]interface{} + out [4]any + out2 [4]any }{ { name: "LeadingZeros", in: 1, - out: [4]interface{}{bits.LeadingZeros8(1), bits.LeadingZeros16(1), bits.LeadingZeros32(1), bits.LeadingZeros64(1)}, + out: [4]any{bits.LeadingZeros8(1), bits.LeadingZeros16(1), bits.LeadingZeros32(1), bits.LeadingZeros64(1)}, }, { name: "TrailingZeros", in: 14, - out: [4]interface{}{bits.TrailingZeros8(14), bits.TrailingZeros16(14), bits.TrailingZeros32(14), bits.TrailingZeros64(14)}, + out: [4]any{bits.TrailingZeros8(14), bits.TrailingZeros16(14), bits.TrailingZeros32(14), bits.TrailingZeros64(14)}, }, { name: "OnesCount", in: 14, - out: [4]interface{}{bits.OnesCount8(14), bits.OnesCount16(14), bits.OnesCount32(14), bits.OnesCount64(14)}, + out: [4]any{bits.OnesCount8(14), bits.OnesCount16(14), bits.OnesCount32(14), bits.OnesCount64(14)}, }, { name: "RotateLeft", in: 15, - out: [4]interface{}{bits.RotateLeft8(15, 2), bits.RotateLeft16(15, 2), bits.RotateLeft32(15, 2), bits.RotateLeft64(15, 2)}, - out2: [4]interface{}{bits.RotateLeft8(15, -2), bits.RotateLeft16(15, -2), bits.RotateLeft32(15, -2), bits.RotateLeft64(15, -2)}, + out: [4]any{bits.RotateLeft8(15, 2), bits.RotateLeft16(15, 2), bits.RotateLeft32(15, 2), bits.RotateLeft64(15, 2)}, + out2: [4]any{bits.RotateLeft8(15, -2), bits.RotateLeft16(15, -2), bits.RotateLeft32(15, -2), bits.RotateLeft64(15, -2)}, }, { name: "Reverse", in: 19, - out: [4]interface{}{bits.Reverse8(19), bits.Reverse16(19), bits.Reverse32(19), bits.Reverse64(19)}, + out: [4]any{bits.Reverse8(19), bits.Reverse16(19), bits.Reverse32(19), bits.Reverse64(19)}, }, { name: "ReverseBytes", in: 15, - out: [4]interface{}{nil, bits.ReverseBytes16(15), bits.ReverseBytes32(15), bits.ReverseBytes64(15)}, + out: [4]any{nil, bits.ReverseBytes16(15), bits.ReverseBytes32(15), bits.ReverseBytes64(15)}, }, { name: "Len", in: 8, - out: [4]interface{}{bits.Len8(8), bits.Len16(8), bits.Len32(8), bits.Len64(8)}, + out: [4]any{bits.Len8(8), bits.Len16(8), bits.Len32(8), bits.Len64(8)}, }, } { for i, size := range []int{8, 16, 32, 64} { diff --git a/src/math/rand/example_test.go b/src/math/rand/example_test.go index 41076135558cb..f691e39d648fd 100644 --- a/src/math/rand/example_test.go +++ b/src/math/rand/example_test.go @@ -57,7 +57,7 @@ func Example_rand() { // The tabwriter here helps us generate aligned output. w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0) defer w.Flush() - show := func(name string, v1, v2, v3 interface{}) { + show := func(name string, v1, v2, v3 any) { fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3) } diff --git a/src/math/rand/regress_test.go b/src/math/rand/regress_test.go index 1f30be85d1ac0..813098ec9c5a7 100644 --- a/src/math/rand/regress_test.go +++ b/src/math/rand/regress_test.go @@ -46,7 +46,7 @@ func TestRegress(t *testing.T) { var args []reflect.Value var argstr string if mt.NumIn() == 1 { - var x interface{} + var x any switch mt.In(0).Kind() { default: t.Fatalf("unexpected argument type for r.%s", m.Name) @@ -83,7 +83,7 @@ func TestRegress(t *testing.T) { args = append(args, reflect.ValueOf(x)) } - var out interface{} + var out any out = mv.Call(args)[0].Interface() if m.Name == "Int" || m.Name == "Intn" { out = int64(out.(int)) @@ -120,7 +120,7 @@ func TestRegress(t *testing.T) { } } -var regressGolden = []interface{}{ +var regressGolden = []any{ float64(4.668112973579268), // ExpFloat64() float64(0.1601593871172866), // ExpFloat64() float64(3.0465834105636), // ExpFloat64() diff --git a/src/mime/quotedprintable/reader_test.go b/src/mime/quotedprintable/reader_test.go index 48a7ff64953be..19e9fea19bbed 100644 --- a/src/mime/quotedprintable/reader_test.go +++ b/src/mime/quotedprintable/reader_test.go @@ -22,7 +22,7 @@ import ( func TestReader(t *testing.T) { tests := []struct { in, want string - err interface{} + err any }{ {in: "", want: ""}, {in: "foo bar", want: "foo bar"}, @@ -160,7 +160,7 @@ func TestExhaustive(t *testing.T) { if err != nil { panic(err) } - qpres := make(chan interface{}, 2) + qpres := make(chan any, 2) go func() { br := bufio.NewReader(stderr) s, _ := br.ReadString('\n') diff --git a/src/mime/type.go b/src/mime/type.go index 26424339af8d0..bdb8bb319af39 100644 --- a/src/mime/type.go +++ b/src/mime/type.go @@ -23,7 +23,7 @@ var ( ) func clearSyncMap(m *sync.Map) { - m.Range(func(k, _ interface{}) bool { + m.Range(func(k, _ any) bool { m.Delete(k) return true }) diff --git a/src/net/http/cgi/host.go b/src/net/http/cgi/host.go index e7124a2ab058a..95b2e13e4efb8 100644 --- a/src/net/http/cgi/host.go +++ b/src/net/http/cgi/host.go @@ -350,7 +350,7 @@ func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { } } -func (h *Handler) printf(format string, v ...interface{}) { +func (h *Handler) printf(format string, v ...any) { if h.Logger != nil { h.Logger.Printf(format, v...) } else { diff --git a/src/net/http/client_test.go b/src/net/http/client_test.go index 62bf9342f45fd..c2ea6f4330403 100644 --- a/src/net/http/client_test.go +++ b/src/net/http/client_test.go @@ -745,7 +745,7 @@ func (j *RecordingJar) Cookies(u *url.URL) []*Cookie { return nil } -func (j *RecordingJar) logf(format string, args ...interface{}) { +func (j *RecordingJar) logf(format string, args ...any) { j.mu.Lock() defer j.mu.Unlock() fmt.Fprintf(&j.log, format, args...) diff --git a/src/net/http/clientserver_test.go b/src/net/http/clientserver_test.go index 125d63566bc78..71b2a32cb4eea 100644 --- a/src/net/http/clientserver_test.go +++ b/src/net/http/clientserver_test.go @@ -81,7 +81,7 @@ func optWithServerLog(lg *log.Logger) func(*httptest.Server) { } } -func newClientServerTest(t *testing.T, h2 bool, h Handler, opts ...interface{}) *clientServerTest { +func newClientServerTest(t *testing.T, h2 bool, h Handler, opts ...any) *clientServerTest { if h2 { CondSkipHTTP2(t) } @@ -189,7 +189,7 @@ type h12Compare struct { ReqFunc reqFunc // optional CheckResponse func(proto string, res *Response) // optional EarlyCheckResponse func(proto string, res *Response) // optional; pre-normalize - Opts []interface{} + Opts []any } func (tt h12Compare) reqFunc() reqFunc { @@ -441,7 +441,7 @@ func TestH12_AutoGzip(t *testing.T) { func TestH12_AutoGzip_Disabled(t *testing.T) { h12Compare{ - Opts: []interface{}{ + Opts: []any{ func(tr *Transport) { tr.DisableCompression = true }, }, Handler: func(w ResponseWriter, r *Request) { @@ -1168,7 +1168,7 @@ func TestInterruptWithPanic_ErrAbortHandler_h1(t *testing.T) { func TestInterruptWithPanic_ErrAbortHandler_h2(t *testing.T) { testInterruptWithPanic(t, h2Mode, ErrAbortHandler) } -func testInterruptWithPanic(t *testing.T, h2 bool, panicValue interface{}) { +func testInterruptWithPanic(t *testing.T, h2 bool, panicValue any) { setParallel(t) const msg = "hello" defer afterTest(t) @@ -1518,7 +1518,7 @@ func TestBidiStreamReverseProxy(t *testing.T) { })) defer proxy.close() - bodyRes := make(chan interface{}, 1) // error or hash.Hash + bodyRes := make(chan any, 1) // error or hash.Hash pr, pw := io.Pipe() req, _ := NewRequest("PUT", proxy.ts.URL, pr) const size = 4 << 20 diff --git a/src/net/http/cookie_test.go b/src/net/http/cookie_test.go index 257dc57420b0d..ccc5f98091d6d 100644 --- a/src/net/http/cookie_test.go +++ b/src/net/http/cookie_test.go @@ -360,7 +360,7 @@ var readSetCookiesTests = []struct { // Header{"Set-Cookie": {"ASP.NET_SessionId=foo; path=/; HttpOnly, .ASPXAUTH=7E3AA; expires=Wed, 07-Mar-2012 14:25:06 GMT; path=/; HttpOnly"}}, } -func toJSON(v interface{}) string { +func toJSON(v any) string { b, err := json.Marshal(v) if err != nil { return fmt.Sprintf("%#v", v) diff --git a/src/net/http/fs_test.go b/src/net/http/fs_test.go index b42ade1e8ac4f..4b01cce72dbf4 100644 --- a/src/net/http/fs_test.go +++ b/src/net/http/fs_test.go @@ -658,7 +658,7 @@ type fakeFileInfo struct { } func (f *fakeFileInfo) Name() string { return f.basename } -func (f *fakeFileInfo) Sys() interface{} { return nil } +func (f *fakeFileInfo) Sys() any { return nil } func (f *fakeFileInfo) ModTime() time.Time { return f.modtime } func (f *fakeFileInfo) IsDir() bool { return f.dir } func (f *fakeFileInfo) Size() int64 { return int64(len(f.contents)) } diff --git a/src/net/http/h2_bundle.go b/src/net/http/h2_bundle.go index bb82f2458589d..83b6d29144c20 100644 --- a/src/net/http/h2_bundle.go +++ b/src/net/http/h2_bundle.go @@ -1049,11 +1049,11 @@ var ( 16 << 10, } http2dataChunkPools = [...]sync.Pool{ - {New: func() interface{} { return make([]byte, 1<<10) }}, - {New: func() interface{} { return make([]byte, 2<<10) }}, - {New: func() interface{} { return make([]byte, 4<<10) }}, - {New: func() interface{} { return make([]byte, 8<<10) }}, - {New: func() interface{} { return make([]byte, 16<<10) }}, + {New: func() any { return make([]byte, 1<<10) }}, + {New: func() any { return make([]byte, 2<<10) }}, + {New: func() any { return make([]byte, 4<<10) }}, + {New: func() any { return make([]byte, 8<<10) }}, + {New: func() any { return make([]byte, 16<<10) }}, } ) @@ -1548,7 +1548,7 @@ func (h *http2FrameHeader) invalidate() { h.valid = false } // frame header bytes. // Used only by ReadFrameHeader. var http2fhBytes = sync.Pool{ - New: func() interface{} { + New: func() any { buf := make([]byte, http2frameHeaderLen) return &buf }, @@ -1655,8 +1655,8 @@ type http2Framer struct { debugFramer *http2Framer // only use for logging written writes debugFramerBuf *bytes.Buffer - debugReadLoggerf func(string, ...interface{}) - debugWriteLoggerf func(string, ...interface{}) + debugReadLoggerf func(string, ...any) + debugWriteLoggerf func(string, ...any) frameCache *http2frameCache // nil if frames aren't reused (default) } @@ -3061,7 +3061,7 @@ func http2curGoroutineID() uint64 { } var http2littleBuf = sync.Pool{ - New: func() interface{} { + New: func() any { buf := make([]byte, 64) return &buf }, @@ -3468,7 +3468,7 @@ func http2newBufferedWriter(w io.Writer) *http2bufferedWriter { const http2bufWriterPoolBufferSize = 4 << 10 var http2bufWriterPool = sync.Pool{ - New: func() interface{} { + New: func() any { return bufio.NewWriterSize(nil, http2bufWriterPoolBufferSize) }, } @@ -3540,7 +3540,7 @@ type http2connectionStater interface { ConnectionState() tls.ConnectionState } -var http2sorterPool = sync.Pool{New: func() interface{} { return new(http2sorter) }} +var http2sorterPool = sync.Pool{New: func() any { return new(http2sorter) }} type http2sorter struct { v []string // owned by sorter @@ -3781,7 +3781,7 @@ var ( ) var http2responseWriterStatePool = sync.Pool{ - New: func() interface{} { + New: func() any { rws := &http2responseWriterState{} rws.bw = bufio.NewWriterSize(http2chunkWriter{rws}, http2handlerChunkWriteSize) return rws @@ -3793,7 +3793,7 @@ var ( http2testHookOnConn func() http2testHookGetServerConn func(*http2serverConn) http2testHookOnPanicMu *sync.Mutex // nil except in tests - http2testHookOnPanic func(sc *http2serverConn, panicVal interface{}) (rePanic bool) + http2testHookOnPanic func(sc *http2serverConn, panicVal any) (rePanic bool) ) // Server is an HTTP/2 server. @@ -4086,7 +4086,7 @@ func (s *http2Server) ServeConn(c net.Conn, opts *http2ServeConnOpts) { streams: make(map[uint32]*http2stream), readFrameCh: make(chan http2readFrameResult), wantWriteFrameCh: make(chan http2FrameWriteRequest, 8), - serveMsgCh: make(chan interface{}, 8), + serveMsgCh: make(chan any, 8), wroteFrameCh: make(chan http2frameWriteResult, 1), // buffered; one send in writeFrameAsync bodyReadCh: make(chan http2bodyReadMsg), // buffering doesn't matter either way doneServing: make(chan struct{}), @@ -4216,7 +4216,7 @@ type http2serverConn struct { wantWriteFrameCh chan http2FrameWriteRequest // from handlers -> serve wroteFrameCh chan http2frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes bodyReadCh chan http2bodyReadMsg // from handlers -> serve - serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop + serveMsgCh chan any // misc messages & code to send to / run on the serve loop flow http2flow // conn-wide (not stream-specific) outbound flow control inflow http2flow // conn-wide inbound flow control tlsState *tls.ConnectionState // shared by all handlers, like net/http @@ -4351,13 +4351,13 @@ func (sc *http2serverConn) setConnState(state ConnState) { } } -func (sc *http2serverConn) vlogf(format string, args ...interface{}) { +func (sc *http2serverConn) vlogf(format string, args ...any) { if http2VerboseLogs { sc.logf(format, args...) } } -func (sc *http2serverConn) logf(format string, args ...interface{}) { +func (sc *http2serverConn) logf(format string, args ...any) { if lg := sc.hs.ErrorLog; lg != nil { lg.Printf(format, args...) } else { @@ -4409,7 +4409,7 @@ func http2isClosedConnError(err error) bool { return false } -func (sc *http2serverConn) condlogf(err error, format string, args ...interface{}) { +func (sc *http2serverConn) condlogf(err error, format string, args ...any) { if err == nil { return } @@ -4679,7 +4679,7 @@ func (sc *http2serverConn) onIdleTimer() { sc.sendServeMsg(http2idleTimerMsg) } func (sc *http2serverConn) onShutdownTimer() { sc.sendServeMsg(http2shutdownTimerMsg) } -func (sc *http2serverConn) sendServeMsg(msg interface{}) { +func (sc *http2serverConn) sendServeMsg(msg any) { sc.serveG.checkNotOn() // NOT select { case sc.serveMsgCh <- msg: @@ -4721,11 +4721,11 @@ func (sc *http2serverConn) readPreface() error { } var http2errChanPool = sync.Pool{ - New: func() interface{} { return make(chan error, 1) }, + New: func() any { return make(chan error, 1) }, } var http2writeDataPool = sync.Pool{ - New: func() interface{} { return new(http2writeData) }, + New: func() any { return new(http2writeData) }, } // writeDataFromHandler writes DATA response frames from a handler on @@ -6712,7 +6712,7 @@ func http2new400Handler(err error) HandlerFunc { // disabled. See comments on h1ServerShutdownChan above for why // the code is written this way. func http2h1ServerKeepAlivesDisabled(hs *Server) bool { - var x interface{} = hs + var x any = hs type I interface { doKeepAlives() bool } @@ -9577,21 +9577,21 @@ var ( http2errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit") ) -func (cc *http2ClientConn) logf(format string, args ...interface{}) { +func (cc *http2ClientConn) logf(format string, args ...any) { cc.t.logf(format, args...) } -func (cc *http2ClientConn) vlogf(format string, args ...interface{}) { +func (cc *http2ClientConn) vlogf(format string, args ...any) { cc.t.vlogf(format, args...) } -func (t *http2Transport) vlogf(format string, args ...interface{}) { +func (t *http2Transport) vlogf(format string, args ...any) { if http2VerboseLogs { t.logf(format, args...) } } -func (t *http2Transport) logf(format string, args ...interface{}) { +func (t *http2Transport) logf(format string, args ...any) { log.Printf(format, args...) } diff --git a/src/net/http/header.go b/src/net/http/header.go index 5c77cbb882666..6487e5025d718 100644 --- a/src/net/http/header.go +++ b/src/net/http/header.go @@ -157,7 +157,7 @@ func (s *headerSorter) Swap(i, j int) { s.kvs[i], s.kvs[j] = s.kvs[j], s.kv func (s *headerSorter) Less(i, j int) bool { return s.kvs[i].key < s.kvs[j].key } var headerSorterPool = sync.Pool{ - New: func() interface{} { return new(headerSorter) }, + New: func() any { return new(headerSorter) }, } // sortedKeyValues returns h's keys sorted in the returned kvs diff --git a/src/net/http/httptrace/trace.go b/src/net/http/httptrace/trace.go index 5777c91747c20..6af30f78d1f4b 100644 --- a/src/net/http/httptrace/trace.go +++ b/src/net/http/httptrace/trace.go @@ -50,7 +50,7 @@ func WithClientTrace(ctx context.Context, trace *ClientTrace) context.Context { } } if trace.DNSDone != nil { - nt.DNSDone = func(netIPs []interface{}, coalesced bool, err error) { + nt.DNSDone = func(netIPs []any, coalesced bool, err error) { addrs := make([]net.IPAddr, len(netIPs)) for i, ip := range netIPs { addrs[i] = ip.(net.IPAddr) diff --git a/src/net/http/httputil/dump_test.go b/src/net/http/httputil/dump_test.go index 366cc8239ac75..5df2ee80752a5 100644 --- a/src/net/http/httputil/dump_test.go +++ b/src/net/http/httputil/dump_test.go @@ -31,7 +31,7 @@ type dumpTest struct { Req *http.Request GetReq func() *http.Request - Body interface{} // optional []byte or func() io.ReadCloser to populate Req.Body + Body any // optional []byte or func() io.ReadCloser to populate Req.Body WantDump string WantDumpOut string diff --git a/src/net/http/httputil/reverseproxy.go b/src/net/http/httputil/reverseproxy.go index 71849bb8f72f5..319e2a3f3f043 100644 --- a/src/net/http/httputil/reverseproxy.go +++ b/src/net/http/httputil/reverseproxy.go @@ -484,7 +484,7 @@ func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int } } -func (p *ReverseProxy) logf(format string, args ...interface{}) { +func (p *ReverseProxy) logf(format string, args ...any) { if p.ErrorLog != nil { p.ErrorLog.Printf(format, args...) } else { diff --git a/src/net/http/omithttp2.go b/src/net/http/omithttp2.go index 63c0e92d6a6f6..3316f55c6dcf5 100644 --- a/src/net/http/omithttp2.go +++ b/src/net/http/omithttp2.go @@ -26,7 +26,7 @@ const http2NextProtoTLS = "h2" type http2Transport struct { MaxHeaderListSize uint32 - ConnPool interface{} + ConnPool any } func (*http2Transport) RoundTrip(*Request) (*Response, error) { panic(noHTTP2) } @@ -56,9 +56,9 @@ type http2Server struct { NewWriteScheduler func() http2WriteScheduler } -type http2WriteScheduler interface{} +type http2WriteScheduler any -func http2NewPriorityWriteScheduler(interface{}) http2WriteScheduler { panic(noHTTP2) } +func http2NewPriorityWriteScheduler(any) http2WriteScheduler { panic(noHTTP2) } func http2ConfigureServer(s *Server, conf *http2Server) error { panic(noHTTP2) } diff --git a/src/net/http/requestwrite_test.go b/src/net/http/requestwrite_test.go index 1157bdfff940a..bdc1e3c508c73 100644 --- a/src/net/http/requestwrite_test.go +++ b/src/net/http/requestwrite_test.go @@ -20,7 +20,7 @@ import ( type reqWriteTest struct { Req Request - Body interface{} // optional []byte or func() io.ReadCloser to populate Req.Body + Body any // optional []byte or func() io.ReadCloser to populate Req.Body // Any of these three may be empty to skip that test. WantWrite string // Request.Write diff --git a/src/net/http/response_test.go b/src/net/http/response_test.go index 8eef65474e4c8..5a735b021587d 100644 --- a/src/net/http/response_test.go +++ b/src/net/http/response_test.go @@ -646,8 +646,8 @@ type readerAndCloser struct { func TestReadResponseCloseInMiddle(t *testing.T) { t.Parallel() for _, test := range readResponseCloseInMiddleTests { - fatalf := func(format string, args ...interface{}) { - args = append([]interface{}{test.chunked, test.compressed}, args...) + fatalf := func(format string, args ...any) { + args = append([]any{test.chunked, test.compressed}, args...) t.Fatalf("on test chunked=%v, compressed=%v: "+format, args...) } checkErr := func(err error, msg string) { @@ -732,7 +732,7 @@ func TestReadResponseCloseInMiddle(t *testing.T) { } } -func diff(t *testing.T, prefix string, have, want interface{}) { +func diff(t *testing.T, prefix string, have, want any) { t.Helper() hv := reflect.ValueOf(have).Elem() wv := reflect.ValueOf(want).Elem() @@ -849,10 +849,10 @@ func TestReadResponseErrors(t *testing.T) { type testCase struct { name string // optional, defaults to in in string - wantErr interface{} // nil, err value, or string substring + wantErr any // nil, err value, or string substring } - status := func(s string, wantErr interface{}) testCase { + status := func(s string, wantErr any) testCase { if wantErr == true { wantErr = "malformed HTTP status code" } @@ -863,7 +863,7 @@ func TestReadResponseErrors(t *testing.T) { } } - version := func(s string, wantErr interface{}) testCase { + version := func(s string, wantErr any) testCase { if wantErr == true { wantErr = "malformed HTTP version" } @@ -874,7 +874,7 @@ func TestReadResponseErrors(t *testing.T) { } } - contentLength := func(status, body string, wantErr interface{}) testCase { + contentLength := func(status, body string, wantErr any) testCase { return testCase{ name: fmt.Sprintf("status %q %q", status, body), in: fmt.Sprintf("HTTP/1.1 %s\r\n%s", status, body), @@ -947,7 +947,7 @@ func TestReadResponseErrors(t *testing.T) { // wantErr can be nil, an error value to match exactly, or type string to // match a substring. -func matchErr(err error, wantErr interface{}) error { +func matchErr(err error, wantErr any) error { if err == nil { if wantErr == nil { return nil diff --git a/src/net/http/roundtrip_js.go b/src/net/http/roundtrip_js.go index dd042e9a01c3e..01c0600ba5550 100644 --- a/src/net/http/roundtrip_js.go +++ b/src/net/http/roundtrip_js.go @@ -118,7 +118,7 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) { errCh = make(chan error, 1) success, failure js.Func ) - success = js.FuncOf(func(this js.Value, args []js.Value) interface{} { + success = js.FuncOf(func(this js.Value, args []js.Value) any { success.Release() failure.Release() @@ -182,7 +182,7 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) { return nil }) - failure = js.FuncOf(func(this js.Value, args []js.Value) interface{} { + failure = js.FuncOf(func(this js.Value, args []js.Value) any { success.Release() failure.Release() errCh <- fmt.Errorf("net/http: fetch() failed: %s", args[0].Get("message").String()) @@ -223,7 +223,7 @@ func (r *streamReader) Read(p []byte) (n int, err error) { bCh = make(chan []byte, 1) errCh = make(chan error, 1) ) - success := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + success := js.FuncOf(func(this js.Value, args []js.Value) any { result := args[0] if result.Get("done").Bool() { errCh <- io.EOF @@ -235,7 +235,7 @@ func (r *streamReader) Read(p []byte) (n int, err error) { return nil }) defer success.Release() - failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + failure := js.FuncOf(func(this js.Value, args []js.Value) any { // Assumes it's a TypeError. See // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError // for more information on this type. See @@ -289,7 +289,7 @@ func (r *arrayReader) Read(p []byte) (n int, err error) { bCh = make(chan []byte, 1) errCh = make(chan error, 1) ) - success := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + success := js.FuncOf(func(this js.Value, args []js.Value) any { // Wrap the input ArrayBuffer with a Uint8Array uint8arrayWrapper := uint8Array.New(args[0]) value := make([]byte, uint8arrayWrapper.Get("byteLength").Int()) @@ -298,7 +298,7 @@ func (r *arrayReader) Read(p []byte) (n int, err error) { return nil }) defer success.Release() - failure := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + failure := js.FuncOf(func(this js.Value, args []js.Value) any { // Assumes it's a TypeError. See // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError // for more information on this type. diff --git a/src/net/http/serve_test.go b/src/net/http/serve_test.go index d46400ef75aa2..fb18cb2c6f5b2 100644 --- a/src/net/http/serve_test.go +++ b/src/net/http/serve_test.go @@ -2147,7 +2147,7 @@ func TestInvalidTrailerClosesConnection(t *testing.T) { // Read and Write. type slowTestConn struct { // over multiple calls to Read, time.Durations are slept, strings are read. - script []interface{} + script []any closec chan bool mu sync.Mutex // guards rd/wd @@ -2239,7 +2239,7 @@ func TestRequestBodyTimeoutClosesConnection(t *testing.T) { defer afterTest(t) for _, handler := range testHandlerBodyConsumers { conn := &slowTestConn{ - script: []interface{}{ + script: []any{ "POST /public HTTP/1.1\r\n" + "Host: test\r\n" + "Content-Length: 10000\r\n" + @@ -2766,7 +2766,7 @@ func TestHandlerPanicWithHijack(t *testing.T) { testHandlerPanic(t, true, h1Mode, nil, "intentional death for testing") } -func testHandlerPanic(t *testing.T, withHijack, h2 bool, wrapper func(Handler) Handler, panicValue interface{}) { +func testHandlerPanic(t *testing.T, withHijack, h2 bool, wrapper func(Handler) Handler, panicValue any) { defer afterTest(t) // Unlike the other tests that set the log output to io.Discard // to quiet the output, this test uses a pipe. The pipe serves three @@ -3934,7 +3934,7 @@ func testTransportAndServerSharedBodyRace(t *testing.T, h2 bool) { // this test fails, it hangs. This helps debugging and I've // added this enough times "temporarily". It now gets added // full time. - errorf := func(format string, args ...interface{}) { + errorf := func(format string, args ...any) { v := fmt.Sprintf(format, args...) println(v) t.Error(v) @@ -3943,10 +3943,10 @@ func testTransportAndServerSharedBodyRace(t *testing.T, h2 bool) { unblockBackend := make(chan bool) backend := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) { gone := rw.(CloseNotifier).CloseNotify() - didCopy := make(chan interface{}) + didCopy := make(chan any) go func() { n, err := io.CopyN(rw, req.Body, bodySize) - didCopy <- []interface{}{n, err} + didCopy <- []any{n, err} }() isGone := false Loop: @@ -4938,7 +4938,7 @@ func TestServerContext_LocalAddrContextKey_h2(t *testing.T) { func testServerContext_LocalAddrContextKey(t *testing.T, h2 bool) { setParallel(t) defer afterTest(t) - ch := make(chan interface{}, 1) + ch := make(chan any, 1) cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { ch <- r.Context().Value(LocalAddrContextKey) })) @@ -6293,7 +6293,7 @@ func testContentEncodingNoSniffing(t *testing.T, h2 bool) { // setting contentEncoding as an interface instead of a string // directly, so as to differentiate between 3 states: // unset, empty string "" and set string "foo/bar". - contentEncoding interface{} + contentEncoding any wantContentType string } diff --git a/src/net/http/server.go b/src/net/http/server.go index f0b0e86e91e96..ddc799bd9e450 100644 --- a/src/net/http/server.go +++ b/src/net/http/server.go @@ -798,7 +798,7 @@ var ( ) var copyBufPool = sync.Pool{ - New: func() interface{} { + New: func() any { b := make([]byte, 32*1024) return &b }, @@ -3190,7 +3190,7 @@ func (srv *Server) SetKeepAlivesEnabled(v bool) { // TODO: Issue 26303: close HTTP/2 conns as soon as they become idle. } -func (s *Server) logf(format string, args ...interface{}) { +func (s *Server) logf(format string, args ...any) { if s.ErrorLog != nil { s.ErrorLog.Printf(format, args...) } else { @@ -3201,7 +3201,7 @@ func (s *Server) logf(format string, args ...interface{}) { // logf prints to the ErrorLog of the *Server associated with request r // via ServerContextKey. If there's no associated server, or if ErrorLog // is nil, logging is done via the log package's standard logger. -func logf(r *Request, format string, args ...interface{}) { +func logf(r *Request, format string, args ...any) { s, _ := r.Context().Value(ServerContextKey).(*Server) if s != nil && s.ErrorLog != nil { s.ErrorLog.Printf(format, args...) @@ -3364,7 +3364,7 @@ func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) { h: make(Header), req: r, } - panicChan := make(chan interface{}, 1) + panicChan := make(chan any, 1) go func() { defer func() { if p := recover(); p != nil { diff --git a/src/net/http/transfer.go b/src/net/http/transfer.go index 2be1c9fa3cc1c..6d51178ee9082 100644 --- a/src/net/http/transfer.go +++ b/src/net/http/transfer.go @@ -73,7 +73,7 @@ type transferWriter struct { ByteReadCh chan readResult // non-nil if probeRequestBody called } -func newTransferWriter(r interface{}) (t *transferWriter, err error) { +func newTransferWriter(r any) (t *transferWriter, err error) { t = &transferWriter{} // Extract relevant fields @@ -481,7 +481,7 @@ func suppressedHeaders(status int) []string { } // msg is *Request or *Response. -func readTransfer(msg interface{}, r *bufio.Reader) (err error) { +func readTransfer(msg any, r *bufio.Reader) (err error) { t := &transferReader{RequestMethod: "GET"} // Unify input @@ -809,7 +809,7 @@ func fixTrailer(header Header, chunked bool) (Header, error) { // and then reads the trailer if necessary. type body struct { src io.Reader - hdr interface{} // non-nil (Response or Request) value means read trailer + hdr any // non-nil (Response or Request) value means read trailer r *bufio.Reader // underlying wire-format reader for the trailer closing bool // is the connection to be closed after reading body? doEarlyClose bool // whether Close should stop early diff --git a/src/net/http/transport.go b/src/net/http/transport.go index f2d2f7928049d..5fe3e6ebb49ac 100644 --- a/src/net/http/transport.go +++ b/src/net/http/transport.go @@ -2668,8 +2668,8 @@ func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err err // a t.Logf func. See export_test.go's Request.WithT method. type tLogKey struct{} -func (tr *transportRequest) logf(format string, args ...interface{}) { - if logf, ok := tr.Request.Context().Value(tLogKey{}).(func(string, ...interface{})); ok { +func (tr *transportRequest) logf(format string, args ...any) { + if logf, ok := tr.Request.Context().Value(tLogKey{}).(func(string, ...any)); ok { logf(time.Now().Format(time.RFC3339Nano)+": "+format, args...) } } diff --git a/src/net/http/transport_test.go b/src/net/http/transport_test.go index 0cdd946de4269..e5d60afb1bb51 100644 --- a/src/net/http/transport_test.go +++ b/src/net/http/transport_test.go @@ -776,7 +776,7 @@ func TestTransportServerClosingUnexpectedly(t *testing.T) { c := ts.Client() fetch := func(n, retries int) string { - condFatalf := func(format string, arg ...interface{}) { + condFatalf := func(format string, arg ...any) { if retries <= 0 { t.Fatalf(format, arg...) } @@ -3514,7 +3514,7 @@ func TestRetryRequestsOnError(t *testing.T) { mu sync.Mutex logbuf bytes.Buffer ) - logf := func(format string, args ...interface{}) { + logf := func(format string, args ...any) { mu.Lock() defer mu.Unlock() fmt.Fprintf(&logbuf, format, args...) @@ -4491,7 +4491,7 @@ func testTransportEventTrace(t *testing.T, h2 bool, noHooks bool) { var mu sync.Mutex // guards buf var buf bytes.Buffer - logf := func(format string, args ...interface{}) { + logf := func(format string, args ...any) { mu.Lock() defer mu.Unlock() fmt.Fprintf(&buf, format, args...) @@ -4650,7 +4650,7 @@ func testTransportEventTrace(t *testing.T, h2 bool, noHooks bool) { func TestTransportEventTraceTLSVerify(t *testing.T) { var mu sync.Mutex var buf bytes.Buffer - logf := func(format string, args ...interface{}) { + logf := func(format string, args ...any) { mu.Lock() defer mu.Unlock() fmt.Fprintf(&buf, format, args...) @@ -4736,7 +4736,7 @@ func TestTransportEventTraceRealDNS(t *testing.T) { var mu sync.Mutex // guards buf var buf bytes.Buffer - logf := func(format string, args ...interface{}) { + logf := func(format string, args ...any) { mu.Lock() defer mu.Unlock() fmt.Fprintf(&buf, format, args...) diff --git a/src/net/ip_test.go b/src/net/ip_test.go index 10e77f3bdb4aa..777461ad27245 100644 --- a/src/net/ip_test.go +++ b/src/net/ip_test.go @@ -718,7 +718,7 @@ var ipAddrScopeTests = []struct { {IP.IsPrivate, IP{0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false}, } -func name(f interface{}) string { +func name(f any) string { return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() } diff --git a/src/net/listen_test.go b/src/net/listen_test.go index 09ffbb31a1ab4..59c0112122bab 100644 --- a/src/net/listen_test.go +++ b/src/net/listen_test.go @@ -379,7 +379,7 @@ func differentWildcardAddr(i, j string) bool { return true } -func checkFirstListener(network string, ln interface{}) error { +func checkFirstListener(network string, ln any) error { switch network { case "tcp": fd := ln.(*TCPListener).fd diff --git a/src/net/lookup.go b/src/net/lookup.go index ff4ddbeb82baa..c7b8dc690590e 100644 --- a/src/net/lookup.go +++ b/src/net/lookup.go @@ -265,7 +265,7 @@ type onlyValuesCtx struct { var _ context.Context = (*onlyValuesCtx)(nil) // Value performs a lookup if the original context hasn't expired. -func (ovc *onlyValuesCtx) Value(key interface{}) interface{} { +func (ovc *onlyValuesCtx) Value(key any) any { select { case <-ovc.lookupValues.Done(): return nil @@ -314,7 +314,7 @@ func (r *Resolver) lookupIPAddr(ctx context.Context, network, host string) ([]IP lookupKey := network + "\000" + host dnsWaitGroup.Add(1) - ch, called := r.getLookupGroup().DoChan(lookupKey, func() (interface{}, error) { + ch, called := r.getLookupGroup().DoChan(lookupKey, func() (any, error) { defer dnsWaitGroup.Done() return testHookLookupIP(lookupGroupCtx, resolverFunc, network, host) }) @@ -377,7 +377,7 @@ func (r *Resolver) lookupIPAddr(ctx context.Context, network, host string) ([]IP // lookupIPReturn turns the return values from singleflight.Do into // the return values from LookupIP. -func lookupIPReturn(addrsi interface{}, err error, shared bool) ([]IPAddr, error) { +func lookupIPReturn(addrsi any, err error, shared bool) ([]IPAddr, error) { if err != nil { return nil, err } @@ -391,8 +391,8 @@ func lookupIPReturn(addrsi interface{}, err error, shared bool) ([]IPAddr, error } // ipAddrsEface returns an empty interface slice of addrs. -func ipAddrsEface(addrs []IPAddr) []interface{} { - s := make([]interface{}, len(addrs)) +func ipAddrsEface(addrs []IPAddr) []any { + s := make([]any, len(addrs)) for i, v := range addrs { s[i] = v } diff --git a/src/net/lookup_test.go b/src/net/lookup_test.go index 5b3a3e24b24c7..d71a18c684d59 100644 --- a/src/net/lookup_test.go +++ b/src/net/lookup_test.go @@ -1057,7 +1057,7 @@ func TestLookupIPAddrPreservesContextValues(t *testing.T) { defer func() { testHookLookupIP = origTestHookLookupIP }() keyValues := []struct { - key, value interface{} + key, value any }{ {"key-1", 12}, {384, "value2"}, diff --git a/src/net/lookup_windows_test.go b/src/net/lookup_windows_test.go index f726ef0f3475b..9254733364595 100644 --- a/src/net/lookup_windows_test.go +++ b/src/net/lookup_windows_test.go @@ -21,7 +21,7 @@ import ( var nslookupTestServers = []string{"mail.golang.com", "gmail.com"} var lookupTestIPs = []string{"8.8.8.8", "1.1.1.1"} -func toJson(v interface{}) string { +func toJson(v any) string { data, _ := json.Marshal(v) return string(data) } diff --git a/src/net/mail/message.go b/src/net/mail/message.go index c120316730c55..985b6fcae271b 100644 --- a/src/net/mail/message.go +++ b/src/net/mail/message.go @@ -35,7 +35,7 @@ var debug = debugT(false) type debugT bool -func (d debugT) Printf(format string, args ...interface{}) { +func (d debugT) Printf(format string, args ...any) { if d { log.Printf(format, args...) } diff --git a/src/net/netip/netip_test.go b/src/net/netip/netip_test.go index 520695cdfb8d2..d988864827b6e 100644 --- a/src/net/netip/netip_test.go +++ b/src/net/netip/netip_test.go @@ -1451,7 +1451,7 @@ type ip4i struct { flags2 byte flags3 byte flags4 byte - ipv6 interface{} + ipv6 any } func newip4i_v4(a, b, c, d byte) ip4i { diff --git a/src/net/platform_test.go b/src/net/platform_test.go index 7d92a0de5de7f..c522ba282915b 100644 --- a/src/net/platform_test.go +++ b/src/net/platform_test.go @@ -173,7 +173,7 @@ func testableListenArgs(network, address, client string) bool { return true } -func condFatalf(t *testing.T, network string, format string, args ...interface{}) { +func condFatalf(t *testing.T, network string, format string, args ...any) { t.Helper() // A few APIs like File and Read/WriteMsg{UDP,IP} are not // fully implemented yet on Plan 9 and Windows. diff --git a/src/net/rpc/client.go b/src/net/rpc/client.go index 60bb2cc99f99b..42d13519b1907 100644 --- a/src/net/rpc/client.go +++ b/src/net/rpc/client.go @@ -27,11 +27,11 @@ var ErrShutdown = errors.New("connection is shut down") // Call represents an active RPC. type Call struct { - ServiceMethod string // The name of the service and method to call. - Args interface{} // The argument to the function (*struct). - Reply interface{} // The reply from the function (*struct). - Error error // After completion, the error status. - Done chan *Call // Receives *Call when Go is complete. + ServiceMethod string // The name of the service and method to call. + Args any // The argument to the function (*struct). + Reply any // The reply from the function (*struct). + Error error // After completion, the error status. + Done chan *Call // Receives *Call when Go is complete. } // Client represents an RPC Client. @@ -61,9 +61,9 @@ type Client struct { // discarded. // See NewClient's comment for information about concurrent access. type ClientCodec interface { - WriteRequest(*Request, interface{}) error + WriteRequest(*Request, any) error ReadResponseHeader(*Response) error - ReadResponseBody(interface{}) error + ReadResponseBody(any) error Close() error } @@ -214,7 +214,7 @@ type gobClientCodec struct { encBuf *bufio.Writer } -func (c *gobClientCodec) WriteRequest(r *Request, body interface{}) (err error) { +func (c *gobClientCodec) WriteRequest(r *Request, body any) (err error) { if err = c.enc.Encode(r); err != nil { return } @@ -228,7 +228,7 @@ func (c *gobClientCodec) ReadResponseHeader(r *Response) error { return c.dec.Decode(r) } -func (c *gobClientCodec) ReadResponseBody(body interface{}) error { +func (c *gobClientCodec) ReadResponseBody(body any) error { return c.dec.Decode(body) } @@ -295,7 +295,7 @@ func (client *Client) Close() error { // the invocation. The done channel will signal when the call is complete by returning // the same Call object. If done is nil, Go will allocate a new channel. // If non-nil, done must be buffered or Go will deliberately crash. -func (client *Client) Go(serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call { +func (client *Client) Go(serviceMethod string, args any, reply any, done chan *Call) *Call { call := new(Call) call.ServiceMethod = serviceMethod call.Args = args @@ -317,7 +317,7 @@ func (client *Client) Go(serviceMethod string, args interface{}, reply interface } // Call invokes the named function, waits for it to complete, and returns its error status. -func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error { +func (client *Client) Call(serviceMethod string, args any, reply any) error { call := <-client.Go(serviceMethod, args, reply, make(chan *Call, 1)).Done return call.Error } diff --git a/src/net/rpc/client_test.go b/src/net/rpc/client_test.go index 38a10ce0b3156..ffc12faedae9c 100644 --- a/src/net/rpc/client_test.go +++ b/src/net/rpc/client_test.go @@ -17,8 +17,8 @@ type shutdownCodec struct { closed bool } -func (c *shutdownCodec) WriteRequest(*Request, interface{}) error { return nil } -func (c *shutdownCodec) ReadResponseBody(interface{}) error { return nil } +func (c *shutdownCodec) WriteRequest(*Request, any) error { return nil } +func (c *shutdownCodec) ReadResponseBody(any) error { return nil } func (c *shutdownCodec) ReadResponseHeader(*Response) error { c.responded <- 1 return errors.New("shutdownCodec ReadResponseHeader") diff --git a/src/net/rpc/debug.go b/src/net/rpc/debug.go index a1d799ff19a14..9e499fd984de6 100644 --- a/src/net/rpc/debug.go +++ b/src/net/rpc/debug.go @@ -72,7 +72,7 @@ type debugHTTP struct { func (server debugHTTP) ServeHTTP(w http.ResponseWriter, req *http.Request) { // Build a sorted version of the data. var services serviceArray - server.serviceMap.Range(func(snamei, svci interface{}) bool { + server.serviceMap.Range(func(snamei, svci any) bool { svc := svci.(*service) ds := debugService{svc, snamei.(string), make(methodArray, 0, len(svc.method))} for mname, method := range svc.method { diff --git a/src/net/rpc/jsonrpc/all_test.go b/src/net/rpc/jsonrpc/all_test.go index 667f839f58022..f4e1278d03ef5 100644 --- a/src/net/rpc/jsonrpc/all_test.go +++ b/src/net/rpc/jsonrpc/all_test.go @@ -28,9 +28,9 @@ type Reply struct { type Arith int type ArithAddResp struct { - Id interface{} `json:"id"` - Result Reply `json:"result"` - Error interface{} `json:"error"` + Id any `json:"id"` + Result Reply `json:"result"` + Error any `json:"error"` } func (t *Arith) Add(args *Args, reply *Reply) error { diff --git a/src/net/rpc/jsonrpc/client.go b/src/net/rpc/jsonrpc/client.go index e6359bed5985c..c473017d26d95 100644 --- a/src/net/rpc/jsonrpc/client.go +++ b/src/net/rpc/jsonrpc/client.go @@ -44,12 +44,12 @@ func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec { } type clientRequest struct { - Method string `json:"method"` - Params [1]interface{} `json:"params"` - Id uint64 `json:"id"` + Method string `json:"method"` + Params [1]any `json:"params"` + Id uint64 `json:"id"` } -func (c *clientCodec) WriteRequest(r *rpc.Request, param interface{}) error { +func (c *clientCodec) WriteRequest(r *rpc.Request, param any) error { c.mutex.Lock() c.pending[r.Seq] = r.ServiceMethod c.mutex.Unlock() @@ -62,7 +62,7 @@ func (c *clientCodec) WriteRequest(r *rpc.Request, param interface{}) error { type clientResponse struct { Id uint64 `json:"id"` Result *json.RawMessage `json:"result"` - Error interface{} `json:"error"` + Error any `json:"error"` } func (r *clientResponse) reset() { @@ -97,7 +97,7 @@ func (c *clientCodec) ReadResponseHeader(r *rpc.Response) error { return nil } -func (c *clientCodec) ReadResponseBody(x interface{}) error { +func (c *clientCodec) ReadResponseBody(x any) error { if x == nil { return nil } diff --git a/src/net/rpc/jsonrpc/server.go b/src/net/rpc/jsonrpc/server.go index 40e4e6f2aa5c1..3ee4ddfef2ac2 100644 --- a/src/net/rpc/jsonrpc/server.go +++ b/src/net/rpc/jsonrpc/server.go @@ -57,8 +57,8 @@ func (r *serverRequest) reset() { type serverResponse struct { Id *json.RawMessage `json:"id"` - Result interface{} `json:"result"` - Error interface{} `json:"error"` + Result any `json:"result"` + Error any `json:"error"` } func (c *serverCodec) ReadRequestHeader(r *rpc.Request) error { @@ -81,7 +81,7 @@ func (c *serverCodec) ReadRequestHeader(r *rpc.Request) error { return nil } -func (c *serverCodec) ReadRequestBody(x interface{}) error { +func (c *serverCodec) ReadRequestBody(x any) error { if x == nil { return nil } @@ -92,14 +92,14 @@ func (c *serverCodec) ReadRequestBody(x interface{}) error { // RPC params is struct. // Unmarshal into array containing struct for now. // Should think about making RPC more general. - var params [1]interface{} + var params [1]any params[0] = x return json.Unmarshal(*c.req.Params, ¶ms) } var null = json.RawMessage([]byte("null")) -func (c *serverCodec) WriteResponse(r *rpc.Response, x interface{}) error { +func (c *serverCodec) WriteResponse(r *rpc.Response, x any) error { c.mutex.Lock() b, ok := c.pending[r.Seq] if !ok { diff --git a/src/net/rpc/server.go b/src/net/rpc/server.go index 223a53cfa7831..d5207a42cf103 100644 --- a/src/net/rpc/server.go +++ b/src/net/rpc/server.go @@ -221,13 +221,13 @@ func isExportedOrBuiltinType(t reflect.Type) bool { // no suitable methods. It also logs the error using package log. // The client accesses each method using a string of the form "Type.Method", // where Type is the receiver's concrete type. -func (server *Server) Register(rcvr interface{}) error { +func (server *Server) Register(rcvr any) error { return server.register(rcvr, "", false) } // RegisterName is like Register but uses the provided name for the type // instead of the receiver's concrete type. -func (server *Server) RegisterName(name string, rcvr interface{}) error { +func (server *Server) RegisterName(name string, rcvr any) error { return server.register(rcvr, name, true) } @@ -235,7 +235,7 @@ func (server *Server) RegisterName(name string, rcvr interface{}) error { // To debug registration, recompile the package with this set to true. const logRegisterError = false -func (server *Server) register(rcvr interface{}, name string, useName bool) error { +func (server *Server) register(rcvr any, name string, useName bool) error { s := new(service) s.typ = reflect.TypeOf(rcvr) s.rcvr = reflect.ValueOf(rcvr) @@ -344,7 +344,7 @@ func suitableMethods(typ reflect.Type, logErr bool) map[string]*methodType { // contains an error when it is used. var invalidRequest = struct{}{} -func (server *Server) sendResponse(sending *sync.Mutex, req *Request, reply interface{}, codec ServerCodec, errmsg string) { +func (server *Server) sendResponse(sending *sync.Mutex, req *Request, reply any, codec ServerCodec, errmsg string) { resp := server.getResponse() // Encode the response header resp.ServiceMethod = req.ServiceMethod @@ -401,11 +401,11 @@ func (c *gobServerCodec) ReadRequestHeader(r *Request) error { return c.dec.Decode(r) } -func (c *gobServerCodec) ReadRequestBody(body interface{}) error { +func (c *gobServerCodec) ReadRequestBody(body any) error { return c.dec.Decode(body) } -func (c *gobServerCodec) WriteResponse(r *Response, body interface{}) (err error) { +func (c *gobServerCodec) WriteResponse(r *Response, body any) (err error) { if err = c.enc.Encode(r); err != nil { if c.encBuf.Flush() == nil { // Gob couldn't encode the header. Should not happen, so if it does, @@ -636,11 +636,11 @@ func (server *Server) Accept(lis net.Listener) { } // Register publishes the receiver's methods in the DefaultServer. -func Register(rcvr interface{}) error { return DefaultServer.Register(rcvr) } +func Register(rcvr any) error { return DefaultServer.Register(rcvr) } // RegisterName is like Register but uses the provided name for the type // instead of the receiver's concrete type. -func RegisterName(name string, rcvr interface{}) error { +func RegisterName(name string, rcvr any) error { return DefaultServer.RegisterName(name, rcvr) } @@ -654,8 +654,8 @@ func RegisterName(name string, rcvr interface{}) error { // See NewClient's comment for information about concurrent access. type ServerCodec interface { ReadRequestHeader(*Request) error - ReadRequestBody(interface{}) error - WriteResponse(*Response, interface{}) error + ReadRequestBody(any) error + WriteResponse(*Response, any) error // Close can be called multiple times and must be idempotent. Close() error diff --git a/src/net/rpc/server_test.go b/src/net/rpc/server_test.go index e5d7fe0c8f55e..dc5f5decc770b 100644 --- a/src/net/rpc/server_test.go +++ b/src/net/rpc/server_test.go @@ -427,7 +427,7 @@ func (codec *CodecEmulator) ReadRequestHeader(req *Request) error { return nil } -func (codec *CodecEmulator) ReadRequestBody(argv interface{}) error { +func (codec *CodecEmulator) ReadRequestBody(argv any) error { if codec.args == nil { return io.ErrUnexpectedEOF } @@ -435,7 +435,7 @@ func (codec *CodecEmulator) ReadRequestBody(argv interface{}) error { return nil } -func (codec *CodecEmulator) WriteResponse(resp *Response, reply interface{}) error { +func (codec *CodecEmulator) WriteResponse(resp *Response, reply any) error { if resp.Error != "" { codec.err = errors.New(resp.Error) } else { @@ -521,7 +521,7 @@ func TestRegistrationError(t *testing.T) { type WriteFailCodec int -func (WriteFailCodec) WriteRequest(*Request, interface{}) error { +func (WriteFailCodec) WriteRequest(*Request, any) error { // the panic caused by this error used to not unlock a lock. return errors.New("fail") } @@ -530,7 +530,7 @@ func (WriteFailCodec) ReadResponseHeader(*Response) error { select {} } -func (WriteFailCodec) ReadResponseBody(interface{}) error { +func (WriteFailCodec) ReadResponseBody(any) error { select {} } diff --git a/src/net/smtp/smtp.go b/src/net/smtp/smtp.go index bcccaa2597959..c1f00a04e1f9e 100644 --- a/src/net/smtp/smtp.go +++ b/src/net/smtp/smtp.go @@ -105,7 +105,7 @@ func (c *Client) Hello(localName string) error { } // cmd is a convenience function that sends a command and returns the response -func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, error) { +func (c *Client) cmd(expectCode int, format string, args ...any) (int, string, error) { id, err := c.Text.Cmd(format, args...) if err != nil { return 0, "", err diff --git a/src/net/textproto/textproto.go b/src/net/textproto/textproto.go index 8fd781e777574..cc1a847e4e1e4 100644 --- a/src/net/textproto/textproto.go +++ b/src/net/textproto/textproto.go @@ -111,7 +111,7 @@ func Dial(network, addr string) (*Conn, error) { // } // return c.ReadCodeLine(250) // -func (c *Conn) Cmd(format string, args ...interface{}) (id uint, err error) { +func (c *Conn) Cmd(format string, args ...any) (id uint, err error) { id = c.Next() c.StartRequest(id) err = c.PrintfLine(format, args...) diff --git a/src/net/textproto/writer.go b/src/net/textproto/writer.go index 33c146c022040..2ece3f511b986 100644 --- a/src/net/textproto/writer.go +++ b/src/net/textproto/writer.go @@ -26,7 +26,7 @@ var crnl = []byte{'\r', '\n'} var dotcrnl = []byte{'.', '\r', '\n'} // PrintfLine writes the formatted output followed by \r\n. -func (w *Writer) PrintfLine(format string, args ...interface{}) error { +func (w *Writer) PrintfLine(format string, args ...any) error { w.closeDot() fmt.Fprintf(w.W, format, args...) w.W.Write(crnl) diff --git a/src/net/url/example_test.go b/src/net/url/example_test.go index 87b6e74a85644..a1913508f72fc 100644 --- a/src/net/url/example_test.go +++ b/src/net/url/example_test.go @@ -365,7 +365,7 @@ func ExampleURL_RequestURI() { // Output: /path?foo=bar } -func toJSON(m interface{}) string { +func toJSON(m any) string { js, err := json.Marshal(m) if err != nil { log.Fatal(err) diff --git a/src/net/url/url_test.go b/src/net/url/url_test.go index 7c807d7a38528..664757b832af0 100644 --- a/src/net/url/url_test.go +++ b/src/net/url/url_test.go @@ -618,7 +618,7 @@ var urltests = []URLTest{ // more useful string for debugging than fmt's struct printer func ufmt(u *URL) string { - var user, pass interface{} + var user, pass any if u.User != nil { user = u.User.Username() if p, ok := u.User.Password(); ok { diff --git a/src/os/dir_unix.go b/src/os/dir_unix.go index 4eeb9ab86ca3a..9b3871a3e866e 100644 --- a/src/os/dir_unix.go +++ b/src/os/dir_unix.go @@ -27,7 +27,7 @@ const ( ) var dirBufPool = sync.Pool{ - New: func() interface{} { + New: func() any { // The buffer must be at least a block long. buf := make([]byte, blockSize) return &buf diff --git a/src/os/env_test.go b/src/os/env_test.go index 11b3b89725d7e..f8d56ef8e022f 100644 --- a/src/os/env_test.go +++ b/src/os/env_test.go @@ -66,7 +66,7 @@ func TestExpand(t *testing.T) { } } -var global interface{} +var global any func BenchmarkExpand(b *testing.B) { b.Run("noop", func(b *testing.B) { diff --git a/src/os/exec.go b/src/os/exec.go index 2beac55f89b67..9eb3166ecb764 100644 --- a/src/os/exec.go +++ b/src/os/exec.go @@ -164,7 +164,7 @@ func (p *ProcessState) Success() bool { // Sys returns system-dependent exit information about // the process. Convert it to the appropriate underlying // type, such as syscall.WaitStatus on Unix, to access its contents. -func (p *ProcessState) Sys() interface{} { +func (p *ProcessState) Sys() any { return p.sys() } @@ -173,6 +173,6 @@ func (p *ProcessState) Sys() interface{} { // type, such as *syscall.Rusage on Unix, to access its contents. // (On Unix, *syscall.Rusage matches struct rusage as defined in the // getrusage(2) manual page.) -func (p *ProcessState) SysUsage() interface{} { +func (p *ProcessState) SysUsage() any { return p.sysUsage() } diff --git a/src/os/exec/exec.go b/src/os/exec/exec.go index 9551c22d6e468..845b737e28fc7 100644 --- a/src/os/exec/exec.go +++ b/src/os/exec/exec.go @@ -216,7 +216,7 @@ func (c *Cmd) String() string { // interfaceEqual protects against panics from doing equality tests on // two interfaces with non-comparable underlying types. -func interfaceEqual(a, b interface{}) bool { +func interfaceEqual(a, b any) bool { defer func() { recover() }() diff --git a/src/os/exec/exec_test.go b/src/os/exec/exec_test.go index 81de018e09e5a..92992a6d664a6 100644 --- a/src/os/exec/exec_test.go +++ b/src/os/exec/exec_test.go @@ -700,7 +700,7 @@ func TestHelperProcess(*testing.T) { cmd, args := args[0], args[1:] switch cmd { case "echo": - iargs := []interface{}{} + iargs := []any{} for _, s := range args { iargs = append(iargs, s) } diff --git a/src/os/exec_plan9.go b/src/os/exec_plan9.go index cc84f97669629..69714ff79830d 100644 --- a/src/os/exec_plan9.go +++ b/src/os/exec_plan9.go @@ -115,11 +115,11 @@ func (p *ProcessState) success() bool { return p.status.ExitStatus() == 0 } -func (p *ProcessState) sys() interface{} { +func (p *ProcessState) sys() any { return p.status } -func (p *ProcessState) sysUsage() interface{} { +func (p *ProcessState) sysUsage() any { return p.status } diff --git a/src/os/exec_posix.go b/src/os/exec_posix.go index 07e2b36f622ab..d619984693517 100644 --- a/src/os/exec_posix.go +++ b/src/os/exec_posix.go @@ -87,11 +87,11 @@ func (p *ProcessState) success() bool { return p.status.ExitStatus() == 0 } -func (p *ProcessState) sys() interface{} { +func (p *ProcessState) sys() any { return p.status } -func (p *ProcessState) sysUsage() interface{} { +func (p *ProcessState) sysUsage() any { return p.rusage } diff --git a/src/os/stat_plan9.go b/src/os/stat_plan9.go index 57ae6fb0bbdf6..e20accf191321 100644 --- a/src/os/stat_plan9.go +++ b/src/os/stat_plan9.go @@ -43,7 +43,7 @@ func fileInfoFromStat(d *syscall.Dir) *fileStat { } // arg is an open *File or a path string. -func dirstat(arg interface{}) (*syscall.Dir, error) { +func dirstat(arg any) (*syscall.Dir, error) { var name string var err error diff --git a/src/os/types_plan9.go b/src/os/types_plan9.go index 125da661b79de..ccf4fd932e7a5 100644 --- a/src/os/types_plan9.go +++ b/src/os/types_plan9.go @@ -15,13 +15,13 @@ type fileStat struct { size int64 mode FileMode modTime time.Time - sys interface{} + sys any } func (fs *fileStat) Size() int64 { return fs.size } func (fs *fileStat) Mode() FileMode { return fs.mode } func (fs *fileStat) ModTime() time.Time { return fs.modTime } -func (fs *fileStat) Sys() interface{} { return fs.sys } +func (fs *fileStat) Sys() any { return fs.sys } func sameFile(fs1, fs2 *fileStat) bool { a := fs1.sys.(*syscall.Dir) diff --git a/src/os/types_unix.go b/src/os/types_unix.go index 105bb78765a33..1b90a5a14157a 100644 --- a/src/os/types_unix.go +++ b/src/os/types_unix.go @@ -23,7 +23,7 @@ type fileStat struct { func (fs *fileStat) Size() int64 { return fs.size } func (fs *fileStat) Mode() FileMode { return fs.mode } func (fs *fileStat) ModTime() time.Time { return fs.modTime } -func (fs *fileStat) Sys() interface{} { return &fs.sys } +func (fs *fileStat) Sys() any { return &fs.sys } func sameFile(fs1, fs2 *fileStat) bool { return fs1.sys.Dev == fs2.sys.Dev && fs1.sys.Ino == fs2.sys.Ino diff --git a/src/os/types_windows.go b/src/os/types_windows.go index 59bf5ca38143d..5443dfedc8ca2 100644 --- a/src/os/types_windows.go +++ b/src/os/types_windows.go @@ -138,7 +138,7 @@ func (fs *fileStat) ModTime() time.Time { } // Sys returns syscall.Win32FileAttributeData for file fs. -func (fs *fileStat) Sys() interface{} { +func (fs *fileStat) Sys() any { return &syscall.Win32FileAttributeData{ FileAttributes: fs.FileAttributes, CreationTime: fs.CreationTime, diff --git a/src/os/user/lookup_unix.go b/src/os/user/lookup_unix.go index e25323fbadbcb..058dab1fb5ad6 100644 --- a/src/os/user/lookup_unix.go +++ b/src/os/user/lookup_unix.go @@ -19,7 +19,7 @@ import ( const userFile = "/etc/passwd" // lineFunc returns a value, an error, or (nil, nil) to skip the row. -type lineFunc func(line []byte) (v interface{}, err error) +type lineFunc func(line []byte) (v any, err error) // readColonFile parses r as an /etc/group or /etc/passwd style file, running // fn for each row. readColonFile returns a value, an error, or (nil, nil) if @@ -27,7 +27,7 @@ type lineFunc func(line []byte) (v interface{}, err error) // // readCols is the minimum number of colon-separated fields that will be passed // to fn; in a long line additional fields may be silently discarded. -func readColonFile(r io.Reader, fn lineFunc, readCols int) (v interface{}, err error) { +func readColonFile(r io.Reader, fn lineFunc, readCols int) (v any, err error) { rd := bufio.NewReader(r) // Read the file line-by-line. @@ -98,7 +98,7 @@ func matchGroupIndexValue(value string, idx int) lineFunc { leadColon = ":" } substr := []byte(leadColon + value + ":") - return func(line []byte) (v interface{}, err error) { + return func(line []byte) (v any, err error) { if !bytes.Contains(line, substr) || bytes.Count(line, colon) < 3 { return } @@ -145,7 +145,7 @@ func matchUserIndexValue(value string, idx int) lineFunc { leadColon = ":" } substr := []byte(leadColon + value + ":") - return func(line []byte) (v interface{}, err error) { + return func(line []byte) (v any, err error) { if !bytes.Contains(line, substr) || bytes.Count(line, colon) < 6 { return } diff --git a/src/plugin/plugin.go b/src/plugin/plugin.go index 4a524bfa3f02e..b2a0fbe3ea2f1 100644 --- a/src/plugin/plugin.go +++ b/src/plugin/plugin.go @@ -22,7 +22,7 @@ type Plugin struct { pluginpath string err string // set if plugin failed to load loaded chan struct{} // closed when loaded - syms map[string]interface{} + syms map[string]any } // Open opens a Go plugin. @@ -69,4 +69,4 @@ func (p *Plugin) Lookup(symName string) (Symbol, error) { // } // *v.(*int) = 7 // f.(func())() // prints "Hello, number 7" -type Symbol interface{} +type Symbol any diff --git a/src/plugin/plugin_dlopen.go b/src/plugin/plugin_dlopen.go index 5fff329fc50a5..c59f11ef719d6 100644 --- a/src/plugin/plugin_dlopen.go +++ b/src/plugin/plugin_dlopen.go @@ -102,7 +102,7 @@ func open(name string) (*Plugin, error) { } // Fill out the value of each plugin symbol. - updatedSyms := map[string]interface{}{} + updatedSyms := map[string]any{} for symName, sym := range syms { isFunc := symName[0] == '.' if isFunc { @@ -147,7 +147,7 @@ var ( ) // lastmoduleinit is defined in package runtime -func lastmoduleinit() (pluginpath string, syms map[string]interface{}, errstr string) +func lastmoduleinit() (pluginpath string, syms map[string]any, errstr string) // doInit is defined in package runtime //go:linkname doInit runtime.doInit diff --git a/src/reflect/abi_test.go b/src/reflect/abi_test.go index 41cfd9d08235a..f39eb5efeae91 100644 --- a/src/reflect/abi_test.go +++ b/src/reflect/abi_test.go @@ -33,7 +33,7 @@ func TestMethodValueCallABI(t *testing.T) { // for us, so there isn't a whole lot to do. Let's just // make sure that we can pass register and stack arguments // through. The exact combination is not super important. - makeMethodValue := func(method string) (*StructWithMethods, interface{}) { + makeMethodValue := func(method string) (*StructWithMethods, any) { s := new(StructWithMethods) v := reflect.ValueOf(s).MethodByName(method) return s, v.Interface() @@ -256,7 +256,7 @@ func TestReflectMakeFuncCallABI(t *testing.T) { }) } -var abiCallTestCases = []interface{}{ +var abiCallTestCases = []any{ passNone, passInt, passInt8, @@ -551,7 +551,7 @@ func passStruct10AndSmall(a Struct10, b byte, c uint) (Struct10, byte, uint) { return a, b, c } -var abiMakeFuncTestCases = []interface{}{ +var abiMakeFuncTestCases = []any{ callArgsNone, callArgsInt, callArgsInt8, diff --git a/src/reflect/all_test.go b/src/reflect/all_test.go index 8c51d8ec2606a..9c8434c22c953 100644 --- a/src/reflect/all_test.go +++ b/src/reflect/all_test.go @@ -29,7 +29,7 @@ import ( "unsafe" ) -var sink interface{} +var sink any func TestBool(t *testing.T) { v := ValueOf(true) @@ -47,7 +47,7 @@ type T struct { } type pair struct { - i interface{} + i any s string } @@ -337,7 +337,7 @@ func TestSetValue(t *testing.T) { } func TestMapIterSet(t *testing.T) { - m := make(map[string]interface{}, len(valueTests)) + m := make(map[string]any, len(valueTests)) for _, tt := range valueTests { m[tt.s] = tt.i } @@ -385,7 +385,7 @@ func TestCanIntUintFloatComplex(t *testing.T) { var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"} var testCases = []struct { - i interface{} + i any want [4]bool }{ // signed integer @@ -691,7 +691,7 @@ func TestAll(t *testing.T) { func TestInterfaceGet(t *testing.T) { var inter struct { - E interface{} + E any } inter.E = 123.456 v1 := ValueOf(&inter) @@ -704,7 +704,7 @@ func TestInterfaceGet(t *testing.T) { func TestInterfaceValue(t *testing.T) { var inter struct { - E interface{} + E any } inter.E = 123.456 v1 := ValueOf(&inter) @@ -720,7 +720,7 @@ func TestInterfaceValue(t *testing.T) { } func TestFunctionValue(t *testing.T) { - var x interface{} = func() {} + var x any = func() {} v := ValueOf(x) if fmt.Sprint(v.Interface()) != fmt.Sprint(x) { t.Fatalf("TestFunction returned wrong pointer") @@ -920,7 +920,7 @@ type Basic struct { type NotBasic Basic type DeepEqualTest struct { - a, b interface{} + a, b any eq bool } @@ -934,11 +934,11 @@ var ( type self struct{} type Loop *Loop -type Loopy interface{} +type Loopy any var loop1, loop2 Loop var loopy1, loopy2 Loopy -var cycleMap1, cycleMap2, cycleMap3 map[string]interface{} +var cycleMap1, cycleMap2, cycleMap3 map[string]any type structWithSelfPtr struct { p *structWithSelfPtr @@ -952,11 +952,11 @@ func init() { loopy1 = &loopy2 loopy2 = &loopy1 - cycleMap1 = map[string]interface{}{} + cycleMap1 = map[string]any{} cycleMap1["cycle"] = cycleMap1 - cycleMap2 = map[string]interface{}{} + cycleMap2 = map[string]any{} cycleMap2["cycle"] = cycleMap2 - cycleMap3 = map[string]interface{}{} + cycleMap3 = map[string]any{} cycleMap3["different"] = cycleMap3 } @@ -1021,7 +1021,7 @@ var deepEqualTests = []DeepEqualTest{ {int32(1), int64(1), false}, {0.5, "hello", false}, {[]int{1, 2, 3}, [3]int{1, 2, 3}, false}, - {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false}, + {&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false}, {Basic{1, 0.5}, NotBasic{1, 0.5}, false}, {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false}, {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false}, @@ -1127,7 +1127,7 @@ func TestDeepEqualUnexportedMap(t *testing.T) { } var deepEqualPerfTests = []struct { - x, y interface{} + x, y any }{ {x: int8(99), y: int8(99)}, {x: []int8{99}, y: []int8{99}}, @@ -1202,7 +1202,7 @@ func BenchmarkDeepEqual(b *testing.B) { } } -func check2ndField(x interface{}, offs uintptr, t *testing.T) { +func check2ndField(x any, offs uintptr, t *testing.T) { s := ValueOf(x) f := s.Type().Field(1) if f.Offset != offs { @@ -1235,14 +1235,14 @@ func TestAlignment(t *testing.T) { check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t) } -func Nil(a interface{}, t *testing.T) { +func Nil(a any, t *testing.T) { n := ValueOf(a).Field(0) if !n.IsNil() { t.Errorf("%v should be nil", a) } } -func NotNil(a interface{}, t *testing.T) { +func NotNil(a any, t *testing.T) { n := ValueOf(a).Field(0) if n.IsNil() { t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String()) @@ -1252,9 +1252,9 @@ func NotNil(a interface{}, t *testing.T) { func TestIsNil(t *testing.T) { // These implement IsNil. // Wrap in extra struct to hide interface type. - doNil := []interface{}{ + doNil := []any{ struct{ x *int }{}, - struct{ x interface{} }{}, + struct{ x any }{}, struct{ x map[string]int }{}, struct{ x func() bool }{}, struct{ x chan int }{}, @@ -1297,7 +1297,7 @@ func TestIsNil(t *testing.T) { NotNil(mi, t) var ii struct { - x interface{} + x any } Nil(ii, t) ii.x = 2 @@ -1313,7 +1313,7 @@ func TestIsNil(t *testing.T) { func TestIsZero(t *testing.T) { for i, tt := range []struct { - x interface{} + x any want bool }{ // Booleans @@ -1425,7 +1425,7 @@ func TestInterfaceExtraction(t *testing.T) { s.W = os.Stdout v := Indirect(ValueOf(&s)).Field(0).Interface() - if v != s.W.(interface{}) { + if v != s.W.(any) { t.Error("Interface() on interface: ", v, s.W) } } @@ -1974,7 +1974,7 @@ func selectWatcher() { // runSelect runs a single select test. // It returns the values returned by Select but also returns // a panic value if the Select panics. -func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) { +func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) { defer func() { panicErr = recover() @@ -2765,7 +2765,7 @@ func TestMethod5(t *testing.T) { var TinterType = TypeOf(new(Tinter)).Elem() - CheckI := func(name string, i interface{}, inc int) { + CheckI := func(name string, i any, inc int) { v := ValueOf(i) CheckV(name, v, inc) CheckV("(i="+name+")", v.Convert(TinterType), inc) @@ -2814,7 +2814,7 @@ func TestInterfaceSet(t *testing.T) { p := &Point{3, 4} var s struct { - I interface{} + I any P interface { Dist(int) int } @@ -2856,7 +2856,7 @@ func TestAnonymousFields(t *testing.T) { } type FTest struct { - s interface{} + s any name string index []int value int @@ -3087,7 +3087,7 @@ func TestImportPath(t *testing.T) { {TypeOf([]byte(nil)), ""}, {TypeOf([]rune(nil)), ""}, {TypeOf(string("")), ""}, - {TypeOf((*interface{})(nil)).Elem(), ""}, + {TypeOf((*any)(nil)).Elem(), ""}, {TypeOf((*byte)(nil)), ""}, {TypeOf((*rune)(nil)), ""}, {TypeOf((*int64)(nil)), ""}, @@ -3290,7 +3290,7 @@ func TestEmbeddedMethods(t *testing.T) { } } -type FuncDDD func(...interface{}) error +type FuncDDD func(...any) error func (f FuncDDD) M() {} @@ -3328,7 +3328,7 @@ func TestPtrToGC(t *testing.T) { tt := TypeOf(T(nil)) pt := PointerTo(tt) const n = 100 - var x []interface{} + var x []any for i := 0; i < n; i++ { v := New(pt) p := new(*uintptr) @@ -3450,7 +3450,7 @@ func noAlloc(t *testing.T, n int, f func(int)) { func TestAllocations(t *testing.T) { noAlloc(t, 100, func(j int) { - var i interface{} + var i any var v Value // We can uncomment this when compiler escape analysis @@ -3624,7 +3624,7 @@ func TestVariadic(t *testing.T) { } b.Reset() - V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})}) + V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})}) if b.String() != "hello, 42 world" { t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world") } @@ -3967,7 +3967,7 @@ func shouldPanic(expect string, f func()) { f() } -func isNonNil(x interface{}) { +func isNonNil(x any) { if x == nil { panic("nil interface") } @@ -3993,7 +3993,7 @@ func TestAlias(t *testing.T) { var V = ValueOf -func EmptyInterfaceV(x interface{}) Value { +func EmptyInterfaceV(x any) Value { return ValueOf(&x).Elem() } @@ -4434,7 +4434,7 @@ var convertTests = []struct { {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))}, {V([]uint(nil)), V([]uint(nil))}, {V([]int(nil)), V([]int(nil))}, - {V(new(interface{})), V(new(interface{}))}, + {V(new(any)), V(new(any))}, {V(new(io.Reader)), V(new(io.Reader))}, {V(new(io.Writer)), V(new(io.Writer))}, @@ -4633,7 +4633,7 @@ var comparableTests = []struct { {TypeOf(NonComparableStruct{}), false}, {TypeOf([10]map[string]int{}), false}, {TypeOf([10]string{}), true}, - {TypeOf(new(interface{})).Elem(), true}, + {TypeOf(new(any)).Elem(), true}, } func TestComparable(t *testing.T) { @@ -4683,7 +4683,7 @@ func TestOverflow(t *testing.T) { } } -func checkSameType(t *testing.T, x Type, y interface{}) { +func checkSameType(t *testing.T, x Type, y any) { if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) { t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y)) } @@ -4693,73 +4693,73 @@ func TestArrayOf(t *testing.T) { // check construction and use of type not in binary tests := []struct { n int - value func(i int) interface{} + value func(i int) any comparable bool want string }{ { n: 0, - value: func(i int) interface{} { type Tint int; return Tint(i) }, + value: func(i int) any { type Tint int; return Tint(i) }, comparable: true, want: "[]", }, { n: 10, - value: func(i int) interface{} { type Tint int; return Tint(i) }, + value: func(i int) any { type Tint int; return Tint(i) }, comparable: true, want: "[0 1 2 3 4 5 6 7 8 9]", }, { n: 10, - value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) }, + value: func(i int) any { type Tfloat float64; return Tfloat(i) }, comparable: true, want: "[0 1 2 3 4 5 6 7 8 9]", }, { n: 10, - value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) }, + value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) }, comparable: true, want: "[0 1 2 3 4 5 6 7 8 9]", }, { n: 10, - value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} }, + value: func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} }, comparable: true, want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]", }, { n: 10, - value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} }, + value: func(i int) any { type Tint int; return []Tint{Tint(i)} }, comparable: false, want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", }, { n: 10, - value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} }, + value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} }, comparable: true, want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]", }, { n: 10, - value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} }, + value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} }, comparable: true, want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", }, { n: 10, - value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} }, + value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} }, comparable: false, want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]", }, { n: 10, - value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} }, + value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} }, comparable: true, want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]", }, { n: 10, - value: func(i int) interface{} { + value: func(i int) any { type TstructUV struct { U int V float64 @@ -4820,7 +4820,7 @@ func TestArrayOfGC(t *testing.T) { type T *uintptr tt := TypeOf(T(nil)) const n = 100 - var x []interface{} + var x []any for i := 0; i < n; i++ { v := New(ArrayOf(n, tt)).Elem() for j := 0; j < v.Len(); j++ { @@ -4984,7 +4984,7 @@ func TestSliceOfGC(t *testing.T) { tt := TypeOf(T(nil)) st := SliceOf(tt) const n = 100 - var x []interface{} + var x []any for i := 0; i < n; i++ { v := MakeSlice(st, n, n) for j := 0; j < v.Len(); j++ { @@ -5174,7 +5174,7 @@ func TestStructOf(t *testing.T) { checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{}) // gccgo used to fail this test. - type structFieldType interface{} + type structFieldType any checkSameType(t, StructOf([]StructField{ { @@ -5350,7 +5350,7 @@ func TestStructOfGC(t *testing.T) { st := StructOf(fields) const n = 10000 - var x []interface{} + var x []any for i := 0; i < n; i++ { v := New(st).Elem() for j := 0; j < v.NumField(); j++ { @@ -5616,7 +5616,7 @@ func TestStructOfWithInterface(t *testing.T) { { name: "StructI", typ: PointerTo(TypeOf(StructI(want))), - val: ValueOf(func() interface{} { + val: ValueOf(func() any { v := StructI(want) return &v }()), @@ -5625,7 +5625,7 @@ func TestStructOfWithInterface(t *testing.T) { { name: "StructIPtr", typ: PointerTo(TypeOf(StructIPtr(want))), - val: ValueOf(func() interface{} { + val: ValueOf(func() any { v := StructIPtr(want) return &v }()), @@ -5887,7 +5887,7 @@ func TestChanOfGC(t *testing.T) { // so we have to save pointers to channels in x; the pointer code will // use the gc info in the newly constructed chan type. const n = 100 - var x []interface{} + var x []any for i := 0; i < n; i++ { v := MakeChan(ct, n) for j := 0; j < n; j++ { @@ -5945,7 +5945,7 @@ func TestMapOfGCKeys(t *testing.T) { // so we have to save pointers to maps in x; the pointer code will // use the gc info in the newly constructed map type. const n = 100 - var x []interface{} + var x []any for i := 0; i < n; i++ { v := MakeMap(mt) for j := 0; j < n; j++ { @@ -5983,7 +5983,7 @@ func TestMapOfGCValues(t *testing.T) { // so we have to save pointers to maps in x; the pointer code will // use the gc info in the newly constructed map type. const n = 100 - var x []interface{} + var x []any for i := 0; i < n; i++ { v := MakeMap(mt) for j := 0; j < n; j++ { @@ -6051,7 +6051,7 @@ func TestFuncOf(t *testing.T) { testCases := []struct { in, out []Type variadic bool - want interface{} + want any }{ {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)}, {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)}, @@ -6544,7 +6544,7 @@ func TestValueString(t *testing.T) { func TestInvalid(t *testing.T) { // Used to have inconsistency between IsValid() and Kind() != Invalid. - type T struct{ v interface{} } + type T struct{ v any } v := ValueOf(T{}).Field(0) if v.IsValid() != true || v.Kind() != Interface { @@ -6562,7 +6562,7 @@ func TestLargeGCProg(t *testing.T) { fv.Call([]Value{ValueOf([256]*byte{})}) } -func fieldIndexRecover(t Type, i int) (recovered interface{}) { +func fieldIndexRecover(t Type, i int) (recovered any) { defer func() { recovered = recover() }() @@ -6736,7 +6736,7 @@ func TestFuncLayout(t *testing.T) { gc: r, }, { - typ: ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(), + typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(), size: 4 * goarch.PtrSize, argsize: 4 * goarch.PtrSize, retOffset: 4 * goarch.PtrSize, @@ -6989,7 +6989,7 @@ func TestGCBits(t *testing.T) { hdr := make([]byte, 8/goarch.PtrSize) - verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) { + verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) { verifyGCBits(t, MapBucketOf(k, e), want) verifyGCBits(t, CachedBucketOf(TypeOf(m)), want) } @@ -7118,7 +7118,7 @@ func TestChanAlloc(t *testing.T) { type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int type nameTest struct { - v interface{} + v any want string } @@ -7130,7 +7130,7 @@ var nameTests = []nameTest{ {(*func() D1)(nil), ""}, {(*<-chan D1)(nil), ""}, {(*chan<- D1)(nil), ""}, - {(*interface{})(nil), ""}, + {(*any)(nil), ""}, {(*interface { F() })(nil), ""}, @@ -7156,7 +7156,7 @@ func TestExported(t *testing.T) { type p3 p type exportTest struct { - v interface{} + v any want bool } exportTests := []exportTest{ @@ -7291,9 +7291,9 @@ func TestSwapper(t *testing.T) { type S string tests := []struct { - in interface{} + in any i, j int - want interface{} + want any }{ { in: []int{1, 20, 300}, @@ -7707,7 +7707,7 @@ func TestSetIter(t *testing.T) { }) // Make sure assignment conversion works. - var x interface{} + var x any y := ValueOf(&x).Elem() y.SetIterKey(i) if _, ok := data[x.(string)]; !ok { diff --git a/src/reflect/deepequal.go b/src/reflect/deepequal.go index b71504fa21117..eaab101221537 100644 --- a/src/reflect/deepequal.go +++ b/src/reflect/deepequal.go @@ -225,7 +225,7 @@ func deepValueEqual(v1, v2 Value, visited map[visit]bool) bool { // values that have been compared before, it treats the values as // equal rather than examining the values to which they point. // This ensures that DeepEqual terminates. -func DeepEqual(x, y interface{}) bool { +func DeepEqual(x, y any) bool { if x == nil || y == nil { return x == y } diff --git a/src/reflect/example_test.go b/src/reflect/example_test.go index 684bafd64869b..3db971c3aeed7 100644 --- a/src/reflect/example_test.go +++ b/src/reflect/example_test.go @@ -14,7 +14,7 @@ import ( ) func ExampleKind() { - for _, v := range []interface{}{"hi", 42, func() {}} { + for _, v := range []any{"hi", 42, func() {}} { switch v := reflect.ValueOf(v); v.Kind() { case reflect.String: fmt.Println(v.String()) @@ -45,7 +45,7 @@ func ExampleMakeFunc() { // When the function is invoked, reflect turns the arguments // into Values, calls swap, and then turns swap's result slice // into the values returned by the new function. - makeSwap := func(fptr interface{}) { + makeSwap := func(fptr any) { // fptr is a pointer to a function. // Obtain the function value itself (likely nil) as a reflect.Value // so that we can query its type and then set the value. diff --git a/src/reflect/export_test.go b/src/reflect/export_test.go index ba7fb68067a93..a5a3c1c27103c 100644 --- a/src/reflect/export_test.go +++ b/src/reflect/export_test.go @@ -88,7 +88,7 @@ func TypeLinks() []string { var GCBits = gcbits -func gcbits(interface{}) []byte // provided by runtime +func gcbits(any) []byte // provided by runtime func MapBucketOf(x, y Type) Type { return bucketOf(x.(*rtype), y.(*rtype)) diff --git a/src/reflect/set_test.go b/src/reflect/set_test.go index 566dc7fb6578a..9ce0e09b82421 100644 --- a/src/reflect/set_test.go +++ b/src/reflect/set_test.go @@ -31,7 +31,7 @@ func TestImplicitMapConversion(t *testing.T) { } { // convert interface key - m := make(map[interface{}]int) + m := make(map[any]int) mv := ValueOf(m) mv.SetMapIndex(ValueOf(1), ValueOf(2)) x, ok := m[1] @@ -44,7 +44,7 @@ func TestImplicitMapConversion(t *testing.T) { } { // convert interface value - m := make(map[int]interface{}) + m := make(map[int]any) mv := ValueOf(m) mv.SetMapIndex(ValueOf(1), ValueOf(2)) x, ok := m[1] @@ -57,7 +57,7 @@ func TestImplicitMapConversion(t *testing.T) { } { // convert both interface key and interface value - m := make(map[interface{}]interface{}) + m := make(map[any]any) mv := ValueOf(m) mv.SetMapIndex(ValueOf(1), ValueOf(2)) x, ok := m[1] @@ -160,8 +160,8 @@ func TestImplicitAppendConversion(t *testing.T) { } var implementsTests = []struct { - x interface{} - t interface{} + x any + t any b bool }{ {new(*bytes.Buffer), new(io.Reader), true}, @@ -198,8 +198,8 @@ func TestImplements(t *testing.T) { } var assignableTests = []struct { - x interface{} - t interface{} + x any + t any b bool }{ {new(chan int), new(<-chan int), true}, @@ -207,13 +207,13 @@ var assignableTests = []struct { {new(*int), new(IntPtr), true}, {new(IntPtr), new(*int), true}, {new(IntPtr), new(IntPtr1), false}, - {new(Ch), new(<-chan interface{}), true}, + {new(Ch), new(<-chan any), true}, // test runs implementsTests too } type IntPtr *int type IntPtr1 *int -type Ch <-chan interface{} +type Ch <-chan any func TestAssignableTo(t *testing.T) { for _, tt := range append(assignableTests, implementsTests...) { diff --git a/src/reflect/swapper.go b/src/reflect/swapper.go index 67b7fbe59be83..745c7b9f4970b 100644 --- a/src/reflect/swapper.go +++ b/src/reflect/swapper.go @@ -14,7 +14,7 @@ import ( // slice. // // Swapper panics if the provided interface is not a slice. -func Swapper(slice interface{}) func(i, j int) { +func Swapper(slice any) func(i, j int) { v := ValueOf(slice) if v.Kind() != Slice { panic(&ValueError{Method: "Swapper", Kind: v.Kind()}) diff --git a/src/reflect/type.go b/src/reflect/type.go index 4701e06c49bb8..6217291a3f2ae 100644 --- a/src/reflect/type.go +++ b/src/reflect/type.go @@ -1414,7 +1414,7 @@ func (t *structType) FieldByName(name string) (f StructField, present bool) { // TypeOf returns the reflection Type that represents the dynamic type of i. // If i is a nil interface value, TypeOf returns nil. -func TypeOf(i interface{}) Type { +func TypeOf(i any) Type { eface := *(*emptyInterface)(unsafe.Pointer(&i)) return toType(eface.typ) } @@ -1458,7 +1458,7 @@ func (t *rtype) ptrTo() *rtype { // Create a new ptrType starting with the description // of an *unsafe.Pointer. - var iptr interface{} = (*unsafe.Pointer)(nil) + var iptr any = (*unsafe.Pointer)(nil) prototype := *(**ptrType)(unsafe.Pointer(&iptr)) pp := *prototype @@ -1876,7 +1876,7 @@ func ChanOf(dir ChanDir, t Type) Type { } // Make a channel type. - var ichan interface{} = (chan unsafe.Pointer)(nil) + var ichan any = (chan unsafe.Pointer)(nil) prototype := *(**chanType)(unsafe.Pointer(&ichan)) ch := *prototype ch.tflag = tflagRegularMemory @@ -1922,7 +1922,7 @@ func MapOf(key, elem Type) Type { // Make a map type. // Note: flag values must match those used in the TMAP case // in ../cmd/compile/internal/reflectdata/reflect.go:writeType. - var imap interface{} = (map[unsafe.Pointer]unsafe.Pointer)(nil) + var imap any = (map[unsafe.Pointer]unsafe.Pointer)(nil) mt := **(**mapType)(unsafe.Pointer(&imap)) mt.str = resolveReflectName(newName(s, "", false)) mt.tflag = 0 @@ -2002,7 +2002,7 @@ func FuncOf(in, out []Type, variadic bool) Type { } // Make a func type. - var ifunc interface{} = (func())(nil) + var ifunc any = (func())(nil) prototype := *(**funcType)(unsafe.Pointer(&ifunc)) n := len(in) + len(out) @@ -2360,7 +2360,7 @@ func SliceOf(t Type) Type { } // Make a slice type. - var islice interface{} = ([]unsafe.Pointer)(nil) + var islice any = ([]unsafe.Pointer)(nil) prototype := *(**sliceType)(unsafe.Pointer(&islice)) slice := *prototype slice.tflag = 0 @@ -2688,7 +2688,7 @@ func StructOf(fields []StructField) Type { size = align(size, uintptr(typalign)) // Make the struct type. - var istruct interface{} = struct{}{} + var istruct any = struct{}{} prototype := *(**structType)(unsafe.Pointer(&istruct)) *typ = *prototype typ.fields = fs @@ -2908,7 +2908,7 @@ func ArrayOf(length int, elem Type) Type { } // Make an array type. - var iarray interface{} = [1]unsafe.Pointer{} + var iarray any = [1]unsafe.Pointer{} prototype := *(**arrayType)(unsafe.Pointer(&iarray)) array := *prototype array.tflag = typ.tflag & tflagRegularMemory @@ -3095,7 +3095,7 @@ func funcLayout(t *funcType, rcvr *rtype) (frametype *rtype, framePool *sync.Poo x.str = resolveReflectName(newName(s, "", false)) // cache result for future callers - framePool = &sync.Pool{New: func() interface{} { + framePool = &sync.Pool{New: func() any { return unsafe_New(x) }} lti, _ := layoutCache.LoadOrStore(k, layoutType{ diff --git a/src/reflect/value.go b/src/reflect/value.go index 02354f27369a2..dcc359dae480b 100644 --- a/src/reflect/value.go +++ b/src/reflect/value.go @@ -104,9 +104,9 @@ func (v Value) pointer() unsafe.Pointer { } // packEface converts v to the empty interface. -func packEface(v Value) interface{} { +func packEface(v Value) any { t := v.typ - var i interface{} + var i any e := (*emptyInterface)(unsafe.Pointer(&i)) // First, fill in the data portion of the interface. switch { @@ -141,7 +141,7 @@ func packEface(v Value) interface{} { } // unpackEface converts the empty interface i to a Value. -func unpackEface(i interface{}) Value { +func unpackEface(i any) Value { e := (*emptyInterface)(unsafe.Pointer(&i)) // NOTE: don't read e.word until we know whether it is really a pointer or not. t := e.typ @@ -1167,11 +1167,11 @@ func (v Value) Elem() Value { k := v.kind() switch k { case Interface: - var eface interface{} + var eface any if v.typ.NumMethod() == 0 { - eface = *(*interface{})(v.ptr) + eface = *(*any)(v.ptr) } else { - eface = (interface{})(*(*interface { + eface = (any)(*(*interface { M() })(v.ptr)) } @@ -1426,11 +1426,11 @@ func (v Value) CanInterface() bool { // var i interface{} = (v's underlying value) // It panics if the Value was obtained by accessing // unexported struct fields. -func (v Value) Interface() (i interface{}) { +func (v Value) Interface() (i any) { return valueInterface(v, true) } -func valueInterface(v Value, safe bool) interface{} { +func valueInterface(v Value, safe bool) any { if v.flag == 0 { panic(&ValueError{"reflect.Value.Interface", Invalid}) } @@ -1449,7 +1449,7 @@ func valueInterface(v Value, safe bool) interface{} { // Empty interface has one layout, all interfaces with // methods have a second layout. if v.NumMethod() == 0 { - return *(*interface{})(v.ptr) + return *(*any)(v.ptr) } return *(*interface { M() @@ -2954,7 +2954,7 @@ func Indirect(v Value) Value { // ValueOf returns a new Value initialized to the concrete value // stored in the interface i. ValueOf(nil) returns the zero Value. -func ValueOf(i interface{}) Value { +func ValueOf(i any) Value { if i == nil { return Value{} } @@ -3051,7 +3051,7 @@ func (v Value) assignTo(context string, dst *rtype, target unsafe.Pointer) Value } x := valueInterface(v, false) if dst.NumMethod() == 0 { - *(*interface{})(target) = x + *(*any)(target) = x } else { ifaceE2I(dst, x, target) } @@ -3382,7 +3382,7 @@ func cvtT2I(v Value, typ Type) Value { target := unsafe_New(typ.common()) x := valueInterface(v, false) if typ.NumMethod() == 0 { - *(*interface{})(target) = x + *(*any)(target) = x } else { ifaceE2I(typ.(*rtype), x, target) } @@ -3481,7 +3481,7 @@ func maplen(m unsafe.Pointer) int //go:linkname call runtime.reflectcall func call(stackArgsType *rtype, f, stackArgs unsafe.Pointer, stackArgsSize, stackRetOffset, frameSize uint32, regArgs *abi.RegArgs) -func ifaceE2I(t *rtype, src interface{}, dst unsafe.Pointer) +func ifaceE2I(t *rtype, src any, dst unsafe.Pointer) // memmove copies size bytes to dst from src. No write barriers are used. //go:noescape @@ -3518,7 +3518,7 @@ func verifyNotInHeapPtr(p uintptr) bool // Dummy annotation marking that the value x escapes, // for use in cases where the reflect code is so clever that // the compiler cannot follow. -func escapes(x interface{}) { +func escapes(x any) { if dummy.b { dummy.x = x } @@ -3526,5 +3526,5 @@ func escapes(x interface{}) { var dummy struct { b bool - x interface{} + x any } diff --git a/src/reflect/visiblefields_test.go b/src/reflect/visiblefields_test.go index 5ae322321b2de..fdedc21f738b5 100644 --- a/src/reflect/visiblefields_test.go +++ b/src/reflect/visiblefields_test.go @@ -17,7 +17,7 @@ type structField struct { var fieldsTests = []struct { testName string - val interface{} + val any expect []structField }{{ testName: "SimpleStruct", @@ -279,7 +279,7 @@ type RS3 struct { RS1 } -type M map[string]interface{} +type M map[string]any type Rec1 struct { *Rec2 diff --git a/src/runtime/abi_test.go b/src/runtime/abi_test.go index 5c1f1f40672a5..f9e8d701ceb88 100644 --- a/src/runtime/abi_test.go +++ b/src/runtime/abi_test.go @@ -78,7 +78,7 @@ func TestFinalizerRegisterABI(t *testing.T) { tests := []struct { name string - fin interface{} + fin any confirmValue int }{ {"Pointer", regFinalizerPointer, -1}, diff --git a/src/runtime/alg.go b/src/runtime/alg.go index 978a3b85dcb3a..5d7d1c77f4dbe 100644 --- a/src/runtime/alg.go +++ b/src/runtime/alg.go @@ -290,7 +290,7 @@ func int64Hash(i uint64, seed uintptr) uintptr { return memhash64(noescape(unsafe.Pointer(&i)), seed) } -func efaceHash(i interface{}, seed uintptr) uintptr { +func efaceHash(i any, seed uintptr) uintptr { return nilinterhash(noescape(unsafe.Pointer(&i)), seed) } diff --git a/src/runtime/cgo.go b/src/runtime/cgo.go index 395d54a66e249..d90468240df97 100644 --- a/src/runtime/cgo.go +++ b/src/runtime/cgo.go @@ -42,7 +42,7 @@ var cgoHasExtraM bool // 2) they keep the argument alive until the call site; the call is emitted after // the end of the (presumed) use of the argument by C. // cgoUse should not actually be called (see cgoAlwaysFalse). -func cgoUse(interface{}) { throw("cgoUse should not be called") } +func cgoUse(any) { throw("cgoUse should not be called") } // cgoAlwaysFalse is a boolean value that is always false. // The cgo-generated code says if cgoAlwaysFalse { cgoUse(p) }. diff --git a/src/runtime/cgo/handle.go b/src/runtime/cgo/handle.go index 726f0a396d19c..d711900d7990e 100644 --- a/src/runtime/cgo/handle.go +++ b/src/runtime/cgo/handle.go @@ -105,7 +105,7 @@ type Handle uintptr // // The intended use is to pass the returned handle to C code, which // passes it back to Go, which calls Value. -func NewHandle(v interface{}) Handle { +func NewHandle(v any) Handle { h := atomic.AddUintptr(&handleIdx, 1) if h == 0 { panic("runtime/cgo: ran out of handle space") @@ -118,7 +118,7 @@ func NewHandle(v interface{}) Handle { // Value returns the associated Go value for a valid handle. // // The method panics if the handle is invalid. -func (h Handle) Value() interface{} { +func (h Handle) Value() any { v, ok := handles.Load(uintptr(h)) if !ok { panic("runtime/cgo: misuse of an invalid Handle") diff --git a/src/runtime/cgo/handle_test.go b/src/runtime/cgo/handle_test.go index 738051a0ea130..b341c8e1e4463 100644 --- a/src/runtime/cgo/handle_test.go +++ b/src/runtime/cgo/handle_test.go @@ -13,8 +13,8 @@ func TestHandle(t *testing.T) { v := 42 tests := []struct { - v1 interface{} - v2 interface{} + v1 any + v2 any }{ {v1: v, v2: v}, {v1: &v, v2: &v}, @@ -44,7 +44,7 @@ func TestHandle(t *testing.T) { } siz := 0 - handles.Range(func(k, v interface{}) bool { + handles.Range(func(k, v any) bool { siz++ return true }) diff --git a/src/runtime/cgocall.go b/src/runtime/cgocall.go index 694b3e66cd519..a0c9560fd0f65 100644 --- a/src/runtime/cgocall.go +++ b/src/runtime/cgocall.go @@ -389,7 +389,7 @@ var racecgosync uint64 // represents possible synchronization in C code // cgoCheckPointer checks if the argument contains a Go pointer that // points to a Go pointer, and panics if it does. -func cgoCheckPointer(ptr interface{}, arg interface{}) { +func cgoCheckPointer(ptr any, arg any) { if debug.cgocheck == 0 { return } @@ -628,7 +628,7 @@ func cgoInRange(p unsafe.Pointer, start, end uintptr) bool { // cgoCheckResult is called to check the result parameter of an // exported Go function. It panics if the result is or contains a Go // pointer. -func cgoCheckResult(val interface{}) { +func cgoCheckResult(val any) { if debug.cgocheck == 0 { return } diff --git a/src/runtime/chan_test.go b/src/runtime/chan_test.go index 355267c5e3a73..9471d4596c2e1 100644 --- a/src/runtime/chan_test.go +++ b/src/runtime/chan_test.go @@ -494,7 +494,7 @@ func TestSelectFairness(t *testing.T) { func TestChanSendInterface(t *testing.T) { type mt struct{} m := &mt{} - c := make(chan interface{}, 1) + c := make(chan any, 1) c <- m select { case c <- m: diff --git a/src/runtime/crash_test.go b/src/runtime/crash_test.go index 01b1ebcdd760f..9b9ab4f3e1b0e 100644 --- a/src/runtime/crash_test.go +++ b/src/runtime/crash_test.go @@ -403,7 +403,7 @@ func TestRuntimePanicWithRuntimeError(t *testing.T) { } } -func panicValue(fn func()) (recovered interface{}) { +func panicValue(fn func()) (recovered any) { defer func() { recovered = recover() }() diff --git a/src/runtime/debug/garbage_test.go b/src/runtime/debug/garbage_test.go index c3501408dd426..7213bbe641dd6 100644 --- a/src/runtime/debug/garbage_test.go +++ b/src/runtime/debug/garbage_test.go @@ -151,8 +151,8 @@ func TestFreeOSMemory(t *testing.T) { } var ( - setGCPercentBallast interface{} - setGCPercentSink interface{} + setGCPercentBallast any + setGCPercentSink any ) func TestSetGCPercent(t *testing.T) { diff --git a/src/runtime/debugcall.go b/src/runtime/debugcall.go index 005a259f2831c..205971c428687 100644 --- a/src/runtime/debugcall.go +++ b/src/runtime/debugcall.go @@ -16,7 +16,7 @@ const ( ) func debugCallV2() -func debugCallPanicked(val interface{}) +func debugCallPanicked(val any) // debugCallCheck checks whether it is safe to inject a debugger // function call with return PC pc. If not, it returns a string diff --git a/src/runtime/debuglog.go b/src/runtime/debuglog.go index 588b54d1f5d8f..75b91c4216d4c 100644 --- a/src/runtime/debuglog.go +++ b/src/runtime/debuglog.go @@ -266,7 +266,7 @@ func (l *dlogger) hex(x uint64) *dlogger { } //go:nosplit -func (l *dlogger) p(x interface{}) *dlogger { +func (l *dlogger) p(x any) *dlogger { if !dlogEnabled { return l } diff --git a/src/runtime/defer_test.go b/src/runtime/defer_test.go index 821db0ca1209b..3a54951c318a5 100644 --- a/src/runtime/defer_test.go +++ b/src/runtime/defer_test.go @@ -433,7 +433,7 @@ func TestIssue43921(t *testing.T) { }() } -func expect(t *testing.T, n int, err interface{}) { +func expect(t *testing.T, n int, err any) { if n != err { t.Fatalf("have %v, want %v", err, n) } diff --git a/src/runtime/error.go b/src/runtime/error.go index 91f83ae126405..43114f092e1cd 100644 --- a/src/runtime/error.go +++ b/src/runtime/error.go @@ -210,7 +210,7 @@ type stringer interface { // printany prints an argument passed to panic. // If panic is called with a value that has a String or Error method, // it has already been converted into a string by preprintpanics. -func printany(i interface{}) { +func printany(i any) { switch v := i.(type) { case nil: print("nil") @@ -253,7 +253,7 @@ func printany(i interface{}) { } } -func printanycustomtype(i interface{}) { +func printanycustomtype(i any) { eface := efaceOf(&i) typestring := eface._type.string() diff --git a/src/runtime/export_debug_test.go b/src/runtime/export_debug_test.go index fffc99d7e5c44..19a9ec135fac0 100644 --- a/src/runtime/export_debug_test.go +++ b/src/runtime/export_debug_test.go @@ -22,7 +22,7 @@ import ( // // On success, InjectDebugCall returns the panic value of fn or nil. // If fn did not panic, its results will be available in args. -func InjectDebugCall(gp *g, fn interface{}, regArgs *abi.RegArgs, stackArgs interface{}, tkill func(tid int) error, returnOnUnsafePoint bool) (interface{}, error) { +func InjectDebugCall(gp *g, fn any, regArgs *abi.RegArgs, stackArgs any, tkill func(tid int) error, returnOnUnsafePoint bool) (any, error) { if gp.lockedm == 0 { return nil, plainError("goroutine not locked to thread") } @@ -96,7 +96,7 @@ type debugCallHandler struct { regArgs *abi.RegArgs argp unsafe.Pointer argSize uintptr - panic interface{} + panic any handleF func(info *siginfo, ctxt *sigctxt, gp2 *g) bool diff --git a/src/runtime/export_debuglog_test.go b/src/runtime/export_debuglog_test.go index 8cd943b43822e..1a9074e646413 100644 --- a/src/runtime/export_debuglog_test.go +++ b/src/runtime/export_debuglog_test.go @@ -14,15 +14,15 @@ const DebugLogStringLimit = debugLogStringLimit var Dlog = dlog -func (l *dlogger) End() { l.end() } -func (l *dlogger) B(x bool) *dlogger { return l.b(x) } -func (l *dlogger) I(x int) *dlogger { return l.i(x) } -func (l *dlogger) I16(x int16) *dlogger { return l.i16(x) } -func (l *dlogger) U64(x uint64) *dlogger { return l.u64(x) } -func (l *dlogger) Hex(x uint64) *dlogger { return l.hex(x) } -func (l *dlogger) P(x interface{}) *dlogger { return l.p(x) } -func (l *dlogger) S(x string) *dlogger { return l.s(x) } -func (l *dlogger) PC(x uintptr) *dlogger { return l.pc(x) } +func (l *dlogger) End() { l.end() } +func (l *dlogger) B(x bool) *dlogger { return l.b(x) } +func (l *dlogger) I(x int) *dlogger { return l.i(x) } +func (l *dlogger) I16(x int16) *dlogger { return l.i16(x) } +func (l *dlogger) U64(x uint64) *dlogger { return l.u64(x) } +func (l *dlogger) Hex(x uint64) *dlogger { return l.hex(x) } +func (l *dlogger) P(x any) *dlogger { return l.p(x) } +func (l *dlogger) S(x string) *dlogger { return l.s(x) } +func (l *dlogger) PC(x uintptr) *dlogger { return l.pc(x) } func DumpDebugLog() string { g := getg() diff --git a/src/runtime/export_test.go b/src/runtime/export_test.go index 4a03f24deddfd..3c8f9eb49b622 100644 --- a/src/runtime/export_test.go +++ b/src/runtime/export_test.go @@ -75,7 +75,7 @@ func Netpoll(delta int64) { }) } -func GCMask(x interface{}) (ret []byte) { +func GCMask(x any) (ret []byte) { systemstack(func() { ret = getgcmask(x) }) @@ -218,7 +218,7 @@ func SetEnvs(e []string) { envs = e } // For benchmarking. -func BenchSetType(n int, x interface{}) { +func BenchSetType(n int, x any) { e := *efaceOf(&x) t := e._type var size uintptr @@ -546,7 +546,7 @@ func MapTombstoneCheck(m map[int]int) { // We should have a series of filled and emptyOne cells, followed by // a series of emptyRest cells. h := *(**hmap)(unsafe.Pointer(&m)) - i := interface{}(m) + i := any(m) t := *(**maptype)(unsafe.Pointer(&i)) for x := 0; x < 1< G is inlined and F is excluded from stack // traces, G still appears. diff --git a/src/runtime/syscall_windows_test.go b/src/runtime/syscall_windows_test.go index 65f74b32fb75f..101e94107c5f5 100644 --- a/src/runtime/syscall_windows_test.go +++ b/src/runtime/syscall_windows_test.go @@ -288,7 +288,7 @@ func TestCallbackInAnotherThread(t *testing.T) { } type cbFunc struct { - goFunc interface{} + goFunc any } func (f cbFunc) cName(cdecl bool) string { diff --git a/src/runtime/testdata/testprog/gc.go b/src/runtime/testdata/testprog/gc.go index 7d371a6a89a0b..215228ea05b11 100644 --- a/src/runtime/testdata/testprog/gc.go +++ b/src/runtime/testdata/testprog/gc.go @@ -90,7 +90,7 @@ func GCFairness2() { runtime.GOMAXPROCS(1) debug.SetGCPercent(1) var count [3]int64 - var sink [3]interface{} + var sink [3]any for i := range count { go func(i int) { for { @@ -266,9 +266,9 @@ func DeferLiveness() { } //go:noinline -func escape(x interface{}) { sink2 = x; sink2 = nil } +func escape(x any) { sink2 = x; sink2 = nil } -var sink2 interface{} +var sink2 any // Test zombie object detection and reporting. func GCZombie() { diff --git a/src/runtime/testdata/testprog/signal.go b/src/runtime/testdata/testprog/signal.go index 417e105c68a5b..cc5ac8af58d81 100644 --- a/src/runtime/testdata/testprog/signal.go +++ b/src/runtime/testdata/testprog/signal.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !windows && !plan9 // +build !windows,!plan9 package main diff --git a/src/runtime/testdata/testprog/syscalls_none.go b/src/runtime/testdata/testprog/syscalls_none.go index 7f8ded3994f18..068bb59af37d1 100644 --- a/src/runtime/testdata/testprog/syscalls_none.go +++ b/src/runtime/testdata/testprog/syscalls_none.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !linux // +build !linux package main diff --git a/src/runtime/testdata/testprogcgo/callback.go b/src/runtime/testdata/testprogcgo/callback.go index be0409f39d241..a2d8a492a47a8 100644 --- a/src/runtime/testdata/testprogcgo/callback.go +++ b/src/runtime/testdata/testprogcgo/callback.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows package main diff --git a/src/runtime/testdata/testprogcgo/catchpanic.go b/src/runtime/testdata/testprogcgo/catchpanic.go index 55a606d1bc854..c722d40a196a9 100644 --- a/src/runtime/testdata/testprogcgo/catchpanic.go +++ b/src/runtime/testdata/testprogcgo/catchpanic.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows package main diff --git a/src/runtime/testdata/testprogcgo/dropm.go b/src/runtime/testdata/testprogcgo/dropm.go index 9e782f504fe12..700b7fa0c23e5 100644 --- a/src/runtime/testdata/testprogcgo/dropm.go +++ b/src/runtime/testdata/testprogcgo/dropm.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows // Test that a sequence of callbacks from C to Go get the same m. diff --git a/src/runtime/testdata/testprogcgo/eintr.go b/src/runtime/testdata/testprogcgo/eintr.go index 1722a75eb9a49..b35b280a76ed0 100644 --- a/src/runtime/testdata/testprogcgo/eintr.go +++ b/src/runtime/testdata/testprogcgo/eintr.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows package main diff --git a/src/runtime/testdata/testprogcgo/exec.go b/src/runtime/testdata/testprogcgo/exec.go index 15723c73695bd..c268bcd9b281e 100644 --- a/src/runtime/testdata/testprogcgo/exec.go +++ b/src/runtime/testdata/testprogcgo/exec.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows package main diff --git a/src/runtime/testdata/testprogcgo/lockosthread.go b/src/runtime/testdata/testprogcgo/lockosthread.go index 36423d9eb0cf3..8fcea35f524a8 100644 --- a/src/runtime/testdata/testprogcgo/lockosthread.go +++ b/src/runtime/testdata/testprogcgo/lockosthread.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows package main diff --git a/src/runtime/testdata/testprogcgo/needmdeadlock.go b/src/runtime/testdata/testprogcgo/needmdeadlock.go index 5a9c359006d7a..b95ec7746895b 100644 --- a/src/runtime/testdata/testprogcgo/needmdeadlock.go +++ b/src/runtime/testdata/testprogcgo/needmdeadlock.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows package main diff --git a/src/runtime/testdata/testprogcgo/numgoroutine.go b/src/runtime/testdata/testprogcgo/numgoroutine.go index 5bdfe52ed41b4..1b9f202f46c82 100644 --- a/src/runtime/testdata/testprogcgo/numgoroutine.go +++ b/src/runtime/testdata/testprogcgo/numgoroutine.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows package main diff --git a/src/runtime/testdata/testprogcgo/raceprof.go b/src/runtime/testdata/testprogcgo/raceprof.go index f7ca629789be7..c098e16196d1e 100644 --- a/src/runtime/testdata/testprogcgo/raceprof.go +++ b/src/runtime/testdata/testprogcgo/raceprof.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build (linux && amd64) || (freebsd && amd64) // +build linux,amd64 freebsd,amd64 package main diff --git a/src/runtime/testdata/testprogcgo/racesig.go b/src/runtime/testdata/testprogcgo/racesig.go index a079b3fd1a531..93526797146be 100644 --- a/src/runtime/testdata/testprogcgo/racesig.go +++ b/src/runtime/testdata/testprogcgo/racesig.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build (linux && amd64) || (freebsd && amd64) // +build linux,amd64 freebsd,amd64 package main diff --git a/src/runtime/testdata/testprogcgo/segv.go b/src/runtime/testdata/testprogcgo/segv.go index 3237a8c69c6f3..0632475228d9b 100644 --- a/src/runtime/testdata/testprogcgo/segv.go +++ b/src/runtime/testdata/testprogcgo/segv.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows package main diff --git a/src/runtime/testdata/testprogcgo/sigstack.go b/src/runtime/testdata/testprogcgo/sigstack.go index 21b668d6c0096..12ca661033b36 100644 --- a/src/runtime/testdata/testprogcgo/sigstack.go +++ b/src/runtime/testdata/testprogcgo/sigstack.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows // Test handling of Go-allocated signal stacks when calling from diff --git a/src/runtime/testdata/testprogcgo/threadpanic.go b/src/runtime/testdata/testprogcgo/threadpanic.go index f9b48a9026da4..2d24fe68eaa36 100644 --- a/src/runtime/testdata/testprogcgo/threadpanic.go +++ b/src/runtime/testdata/testprogcgo/threadpanic.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 // +build !plan9 package main diff --git a/src/runtime/testdata/testprogcgo/threadpprof.go b/src/runtime/testdata/testprogcgo/threadpprof.go index e093f67e1e69d..ec5e750da9dd2 100644 --- a/src/runtime/testdata/testprogcgo/threadpprof.go +++ b/src/runtime/testdata/testprogcgo/threadpprof.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !plan9 && !windows // +build !plan9,!windows package main @@ -108,7 +109,7 @@ func pprofThread() { C.runCPUHogThread() }) - time.Sleep(1*time.Second) + time.Sleep(1 * time.Second) pprof.StopCPUProfile() diff --git a/src/runtime/testdata/testprogcgo/threadprof.go b/src/runtime/testdata/testprogcgo/threadprof.go index 2d4c1039fb737..8081173c0f45e 100644 --- a/src/runtime/testdata/testprogcgo/threadprof.go +++ b/src/runtime/testdata/testprogcgo/threadprof.go @@ -5,8 +5,8 @@ // We only build this file with the tag "threadprof", since it starts // a thread running a busy loop at constructor time. -// +build !plan9,!windows -// +build threadprof +//go:build !plan9 && !windows && threadprof +// +build !plan9,!windows,threadprof package main diff --git a/src/runtime/testdata/testprognet/signal.go b/src/runtime/testdata/testprognet/signal.go index 4d2de79d97c03..dfa2e10e7ab93 100644 --- a/src/runtime/testdata/testprognet/signal.go +++ b/src/runtime/testdata/testprognet/signal.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !windows && !plan9 // +build !windows,!plan9 // This is in testprognet instead of testprog because testprog diff --git a/src/runtime/testdata/testprognet/signalexec.go b/src/runtime/testdata/testprognet/signalexec.go index 4a988ef6c1da2..62ebce7176f22 100644 --- a/src/runtime/testdata/testprognet/signalexec.go +++ b/src/runtime/testdata/testprognet/signalexec.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd // +build darwin dragonfly freebsd linux netbsd openbsd // This is in testprognet instead of testprog because testprog diff --git a/src/runtime/testdata/testwinlib/main.go b/src/runtime/testdata/testwinlib/main.go index 400eaa1c82dfa..025ef913e5e97 100644 --- a/src/runtime/testdata/testwinlib/main.go +++ b/src/runtime/testdata/testwinlib/main.go @@ -1,3 +1,4 @@ +//go:build windows && cgo // +build windows,cgo package main diff --git a/src/runtime/time.go b/src/runtime/time.go index 46e9a8c2abb7e..a9ad62077644e 100644 --- a/src/runtime/time.go +++ b/src/runtime/time.go @@ -28,8 +28,8 @@ type timer struct { // when must be positive on an active timer. when int64 period int64 - f func(interface{}, uintptr) - arg interface{} + f func(any, uintptr) + arg any seq uintptr // What to set the when field to in timerModifiedXX status. @@ -232,14 +232,14 @@ func resetTimer(t *timer, when int64) bool { // modTimer modifies an existing timer. //go:linkname modTimer time.modTimer -func modTimer(t *timer, when, period int64, f func(interface{}, uintptr), arg interface{}, seq uintptr) { +func modTimer(t *timer, when, period int64, f func(any, uintptr), arg any, seq uintptr) { modtimer(t, when, period, f, arg, seq) } // Go runtime. // Ready the goroutine arg. -func goroutineReady(arg interface{}, seq uintptr) { +func goroutineReady(arg any, seq uintptr) { goready(arg.(*g), 0) } @@ -421,7 +421,7 @@ func dodeltimer0(pp *p) { // modtimer modifies an existing timer. // This is called by the netpoll code or time.Ticker.Reset or time.Timer.Reset. // Reports whether the timer was modified before it was run. -func modtimer(t *timer, when, period int64, f func(interface{}, uintptr), arg interface{}, seq uintptr) bool { +func modtimer(t *timer, when, period int64, f func(any, uintptr), arg any, seq uintptr) bool { if when <= 0 { throw("timer when must be positive") } diff --git a/src/runtime/trace/annotation.go b/src/runtime/trace/annotation.go index 6e18bfb75554b..d05b5e2261309 100644 --- a/src/runtime/trace/annotation.go +++ b/src/runtime/trace/annotation.go @@ -98,7 +98,7 @@ func Log(ctx context.Context, category, message string) { } // Logf is like Log, but the value is formatted using the specified format spec. -func Logf(ctx context.Context, category, format string, args ...interface{}) { +func Logf(ctx context.Context, category, format string, args ...any) { if IsEnabled() { // Ideally this should be just Log, but that will // add one more frame in the stack trace. diff --git a/src/sort/slice.go b/src/sort/slice.go index 992ad1559df58..ba5c2e2f3d3f1 100644 --- a/src/sort/slice.go +++ b/src/sort/slice.go @@ -13,7 +13,7 @@ package sort // // The less function must satisfy the same requirements as // the Interface type's Less method. -func Slice(x interface{}, less func(i, j int) bool) { +func Slice(x any, less func(i, j int) bool) { rv := reflectValueOf(x) swap := reflectSwapper(x) length := rv.Len() @@ -26,7 +26,7 @@ func Slice(x interface{}, less func(i, j int) bool) { // // The less function must satisfy the same requirements as // the Interface type's Less method. -func SliceStable(x interface{}, less func(i, j int) bool) { +func SliceStable(x any, less func(i, j int) bool) { rv := reflectValueOf(x) swap := reflectSwapper(x) stable_func(lessSwap{less, swap}, rv.Len()) @@ -34,7 +34,7 @@ func SliceStable(x interface{}, less func(i, j int) bool) { // SliceIsSorted reports whether the slice x is sorted according to the provided less function. // It panics if x is not a slice. -func SliceIsSorted(x interface{}, less func(i, j int) bool) bool { +func SliceIsSorted(x any, less func(i, j int) bool) bool { rv := reflectValueOf(x) n := rv.Len() for i := n - 1; i > 0; i-- { diff --git a/src/sort/slice_go14.go b/src/sort/slice_go14.go index 5d5949f3cade5..e4773676185bc 100644 --- a/src/sort/slice_go14.go +++ b/src/sort/slice_go14.go @@ -11,7 +11,7 @@ import "reflect" var reflectValueOf = reflect.ValueOf -func reflectSwapper(x interface{}) func(int, int) { +func reflectSwapper(x any) func(int, int) { v := reflectValueOf(x) tmp := reflect.New(v.Type().Elem()).Elem() return func(i, j int) { diff --git a/src/strings/export_test.go b/src/strings/export_test.go index b39cee6b1ded1..81d1cab9d0064 100644 --- a/src/strings/export_test.go +++ b/src/strings/export_test.go @@ -4,7 +4,7 @@ package strings -func (r *Replacer) Replacer() interface{} { +func (r *Replacer) Replacer() any { r.once.Do(r.buildOnce) return r.r } diff --git a/src/strings/reader_test.go b/src/strings/reader_test.go index 5adea6f7ab2b3..dc99f9c248581 100644 --- a/src/strings/reader_test.go +++ b/src/strings/reader_test.go @@ -77,7 +77,7 @@ func TestReaderAt(t *testing.T) { off int64 n int want string - wanterr interface{} + wanterr any }{ {0, 10, "0123456789", nil}, {1, 10, "123456789", io.EOF}, diff --git a/src/sync/atomic/atomic_test.go b/src/sync/atomic/atomic_test.go index 4b8c2a58f34b4..8a53094cb787e 100644 --- a/src/sync/atomic/atomic_test.go +++ b/src/sync/atomic/atomic_test.go @@ -32,7 +32,7 @@ const ( ) // Do the 64-bit functions panic? If so, don't bother testing. -var test64err = func() (err interface{}) { +var test64err = func() (err any) { defer func() { err = recover() }() diff --git a/src/sync/atomic/value.go b/src/sync/atomic/value.go index af6295de91e19..f18b7ee095e07 100644 --- a/src/sync/atomic/value.go +++ b/src/sync/atomic/value.go @@ -14,7 +14,7 @@ import ( // // A Value must not be copied after first use. type Value struct { - v interface{} + v any } // ifaceWords is interface{} internal representation. @@ -25,7 +25,7 @@ type ifaceWords struct { // Load returns the value set by the most recent Store. // It returns nil if there has been no call to Store for this Value. -func (v *Value) Load() (val interface{}) { +func (v *Value) Load() (val any) { vp := (*ifaceWords)(unsafe.Pointer(v)) typ := LoadPointer(&vp.typ) if typ == nil || typ == unsafe.Pointer(&firstStoreInProgress) { @@ -44,7 +44,7 @@ var firstStoreInProgress byte // Store sets the value of the Value to x. // All calls to Store for a given Value must use values of the same concrete type. // Store of an inconsistent type panics, as does Store(nil). -func (v *Value) Store(val interface{}) { +func (v *Value) Store(val any) { if val == nil { panic("sync/atomic: store of nil value into Value") } @@ -87,7 +87,7 @@ func (v *Value) Store(val interface{}) { // // All calls to Swap for a given Value must use values of the same concrete // type. Swap of an inconsistent type panics, as does Swap(nil). -func (v *Value) Swap(new interface{}) (old interface{}) { +func (v *Value) Swap(new any) (old any) { if new == nil { panic("sync/atomic: swap of nil value into Value") } @@ -132,7 +132,7 @@ func (v *Value) Swap(new interface{}) (old interface{}) { // All calls to CompareAndSwap for a given Value must use values of the same // concrete type. CompareAndSwap of an inconsistent type panics, as does // CompareAndSwap(old, nil). -func (v *Value) CompareAndSwap(old, new interface{}) (swapped bool) { +func (v *Value) CompareAndSwap(old, new any) (swapped bool) { if new == nil { panic("sync/atomic: compare and swap of nil value into Value") } @@ -179,7 +179,7 @@ func (v *Value) CompareAndSwap(old, new interface{}) (swapped bool) { // CompareAndSwapPointer below only ensures vp.data // has not changed since LoadPointer. data := LoadPointer(&vp.data) - var i interface{} + var i any (*ifaceWords)(unsafe.Pointer(&i)).typ = typ (*ifaceWords)(unsafe.Pointer(&i)).data = data if i != old { diff --git a/src/sync/atomic/value_test.go b/src/sync/atomic/value_test.go index a5e717d6e0ccd..721da965e3580 100644 --- a/src/sync/atomic/value_test.go +++ b/src/sync/atomic/value_test.go @@ -80,7 +80,7 @@ func TestValuePanic(t *testing.T) { } func TestValueConcurrent(t *testing.T) { - tests := [][]interface{}{ + tests := [][]any{ {uint16(0), ^uint16(0), uint16(1 + 2<<8), uint16(3 + 4<<8)}, {uint32(0), ^uint32(0), uint32(1 + 2<<16), uint32(3 + 4<<16)}, {uint64(0), ^uint64(0), uint64(1 + 2<<32), uint64(3 + 4<<32)}, @@ -138,10 +138,10 @@ func BenchmarkValueRead(b *testing.B) { } var Value_SwapTests = []struct { - init interface{} - new interface{} - want interface{} - err interface{} + init any + new any + want any + err any }{ {init: nil, new: nil, err: "sync/atomic: swap of nil value into Value"}, {init: nil, new: true, want: nil, err: nil}, @@ -207,11 +207,11 @@ func TestValueSwapConcurrent(t *testing.T) { var heapA, heapB = struct{ uint }{0}, struct{ uint }{0} var Value_CompareAndSwapTests = []struct { - init interface{} - new interface{} - old interface{} + init any + new any + old any want bool - err interface{} + err any }{ {init: nil, new: nil, old: nil, err: "sync/atomic: compare and swap of nil value into Value"}, {init: nil, new: true, old: "", err: "sync/atomic: compare and swap of inconsistently typed values into Value"}, diff --git a/src/sync/example_pool_test.go b/src/sync/example_pool_test.go index 8288d41e8c084..2fb4c1e6b913b 100644 --- a/src/sync/example_pool_test.go +++ b/src/sync/example_pool_test.go @@ -13,7 +13,7 @@ import ( ) var bufPool = sync.Pool{ - New: func() interface{} { + New: func() any { // The Pool's New function should generally only return pointer // types, since a pointer can be put into the return interface // value without an allocation: diff --git a/src/sync/export_test.go b/src/sync/export_test.go index ffbe567464062..c020ef737da40 100644 --- a/src/sync/export_test.go +++ b/src/sync/export_test.go @@ -12,9 +12,9 @@ var Runtime_procUnpin = runtime_procUnpin // poolDequeue testing. type PoolDequeue interface { - PushHead(val interface{}) bool - PopHead() (interface{}, bool) - PopTail() (interface{}, bool) + PushHead(val any) bool + PopHead() (any, bool) + PopTail() (any, bool) } func NewPoolDequeue(n int) PoolDequeue { @@ -27,15 +27,15 @@ func NewPoolDequeue(n int) PoolDequeue { return d } -func (d *poolDequeue) PushHead(val interface{}) bool { +func (d *poolDequeue) PushHead(val any) bool { return d.pushHead(val) } -func (d *poolDequeue) PopHead() (interface{}, bool) { +func (d *poolDequeue) PopHead() (any, bool) { return d.popHead() } -func (d *poolDequeue) PopTail() (interface{}, bool) { +func (d *poolDequeue) PopTail() (any, bool) { return d.popTail() } @@ -43,15 +43,15 @@ func NewPoolChain() PoolDequeue { return new(poolChain) } -func (c *poolChain) PushHead(val interface{}) bool { +func (c *poolChain) PushHead(val any) bool { c.pushHead(val) return true } -func (c *poolChain) PopHead() (interface{}, bool) { +func (c *poolChain) PopHead() (any, bool) { return c.popHead() } -func (c *poolChain) PopTail() (interface{}, bool) { +func (c *poolChain) PopTail() (any, bool) { return c.popTail() } diff --git a/src/sync/map.go b/src/sync/map.go index 7a6c82e5c3951..2fa3253429114 100644 --- a/src/sync/map.go +++ b/src/sync/map.go @@ -48,7 +48,7 @@ type Map struct { // // If the dirty map is nil, the next write to the map will initialize it by // making a shallow copy of the clean map, omitting stale entries. - dirty map[interface{}]*entry + dirty map[any]*entry // misses counts the number of loads since the read map was last updated that // needed to lock mu to determine whether the key was present. @@ -61,13 +61,13 @@ type Map struct { // readOnly is an immutable struct stored atomically in the Map.read field. type readOnly struct { - m map[interface{}]*entry + m map[any]*entry amended bool // true if the dirty map contains some key not in m. } // expunged is an arbitrary pointer that marks entries which have been deleted // from the dirty map. -var expunged = unsafe.Pointer(new(interface{})) +var expunged = unsafe.Pointer(new(any)) // An entry is a slot in the map corresponding to a particular key. type entry struct { @@ -93,14 +93,14 @@ type entry struct { p unsafe.Pointer // *interface{} } -func newEntry(i interface{}) *entry { +func newEntry(i any) *entry { return &entry{p: unsafe.Pointer(&i)} } // Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map. -func (m *Map) Load(key interface{}) (value interface{}, ok bool) { +func (m *Map) Load(key any) (value any, ok bool) { read, _ := m.read.Load().(readOnly) e, ok := read.m[key] if !ok && read.amended { @@ -125,16 +125,16 @@ func (m *Map) Load(key interface{}) (value interface{}, ok bool) { return e.load() } -func (e *entry) load() (value interface{}, ok bool) { +func (e *entry) load() (value any, ok bool) { p := atomic.LoadPointer(&e.p) if p == nil || p == expunged { return nil, false } - return *(*interface{})(p), true + return *(*any)(p), true } // Store sets the value for a key. -func (m *Map) Store(key, value interface{}) { +func (m *Map) Store(key, value any) { read, _ := m.read.Load().(readOnly) if e, ok := read.m[key]; ok && e.tryStore(&value) { return @@ -167,7 +167,7 @@ func (m *Map) Store(key, value interface{}) { // // If the entry is expunged, tryStore returns false and leaves the entry // unchanged. -func (e *entry) tryStore(i *interface{}) bool { +func (e *entry) tryStore(i *any) bool { for { p := atomic.LoadPointer(&e.p) if p == expunged { @@ -190,14 +190,14 @@ func (e *entry) unexpungeLocked() (wasExpunged bool) { // storeLocked unconditionally stores a value to the entry. // // The entry must be known not to be expunged. -func (e *entry) storeLocked(i *interface{}) { +func (e *entry) storeLocked(i *any) { atomic.StorePointer(&e.p, unsafe.Pointer(i)) } // LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. -func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) { +func (m *Map) LoadOrStore(key, value any) (actual any, loaded bool) { // Avoid locking if it's a clean hit. read, _ := m.read.Load().(readOnly) if e, ok := read.m[key]; ok { @@ -237,13 +237,13 @@ func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bo // // If the entry is expunged, tryLoadOrStore leaves the entry unchanged and // returns with ok==false. -func (e *entry) tryLoadOrStore(i interface{}) (actual interface{}, loaded, ok bool) { +func (e *entry) tryLoadOrStore(i any) (actual any, loaded, ok bool) { p := atomic.LoadPointer(&e.p) if p == expunged { return nil, false, false } if p != nil { - return *(*interface{})(p), true, true + return *(*any)(p), true, true } // Copy the interface after the first load to make this method more amenable @@ -259,14 +259,14 @@ func (e *entry) tryLoadOrStore(i interface{}) (actual interface{}, loaded, ok bo return nil, false, false } if p != nil { - return *(*interface{})(p), true, true + return *(*any)(p), true, true } } } // LoadAndDelete deletes the value for a key, returning the previous value if any. // The loaded result reports whether the key was present. -func (m *Map) LoadAndDelete(key interface{}) (value interface{}, loaded bool) { +func (m *Map) LoadAndDelete(key any) (value any, loaded bool) { read, _ := m.read.Load().(readOnly) e, ok := read.m[key] if !ok && read.amended { @@ -290,18 +290,18 @@ func (m *Map) LoadAndDelete(key interface{}) (value interface{}, loaded bool) { } // Delete deletes the value for a key. -func (m *Map) Delete(key interface{}) { +func (m *Map) Delete(key any) { m.LoadAndDelete(key) } -func (e *entry) delete() (value interface{}, ok bool) { +func (e *entry) delete() (value any, ok bool) { for { p := atomic.LoadPointer(&e.p) if p == nil || p == expunged { return nil, false } if atomic.CompareAndSwapPointer(&e.p, p, nil) { - return *(*interface{})(p), true + return *(*any)(p), true } } } @@ -317,7 +317,7 @@ func (e *entry) delete() (value interface{}, ok bool) { // // Range may be O(N) with the number of elements in the map even if f returns // false after a constant number of calls. -func (m *Map) Range(f func(key, value interface{}) bool) { +func (m *Map) Range(f func(key, value any) bool) { // We need to be able to iterate over all of the keys that were already // present at the start of the call to Range. // If read.amended is false, then read.m satisfies that property without @@ -366,7 +366,7 @@ func (m *Map) dirtyLocked() { } read, _ := m.read.Load().(readOnly) - m.dirty = make(map[interface{}]*entry, len(read.m)) + m.dirty = make(map[any]*entry, len(read.m)) for k, e := range read.m { if !e.tryExpungeLocked() { m.dirty[k] = e diff --git a/src/sync/map_bench_test.go b/src/sync/map_bench_test.go index cf0a3d7fdedc8..e7b0e6039c44d 100644 --- a/src/sync/map_bench_test.go +++ b/src/sync/map_bench_test.go @@ -216,7 +216,7 @@ func BenchmarkRange(b *testing.B) { perG: func(b *testing.B, pb *testing.PB, i int, m mapInterface) { for ; pb.Next(); i++ { - m.Range(func(_, _ interface{}) bool { return true }) + m.Range(func(_, _ any) bool { return true }) } }, }) @@ -263,7 +263,7 @@ func BenchmarkAdversarialDelete(b *testing.B) { m.Load(i) if i%mapSize == 0 { - m.Range(func(k, _ interface{}) bool { + m.Range(func(k, _ any) bool { m.Delete(k) return false }) diff --git a/src/sync/map_reference_test.go b/src/sync/map_reference_test.go index d105a24e926e3..1122b40b9b835 100644 --- a/src/sync/map_reference_test.go +++ b/src/sync/map_reference_test.go @@ -13,43 +13,43 @@ import ( // mapInterface is the interface Map implements. type mapInterface interface { - Load(interface{}) (interface{}, bool) - Store(key, value interface{}) - LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) - LoadAndDelete(key interface{}) (value interface{}, loaded bool) - Delete(interface{}) - Range(func(key, value interface{}) (shouldContinue bool)) + Load(any) (any, bool) + Store(key, value any) + LoadOrStore(key, value any) (actual any, loaded bool) + LoadAndDelete(key any) (value any, loaded bool) + Delete(any) + Range(func(key, value any) (shouldContinue bool)) } // RWMutexMap is an implementation of mapInterface using a sync.RWMutex. type RWMutexMap struct { mu sync.RWMutex - dirty map[interface{}]interface{} + dirty map[any]any } -func (m *RWMutexMap) Load(key interface{}) (value interface{}, ok bool) { +func (m *RWMutexMap) Load(key any) (value any, ok bool) { m.mu.RLock() value, ok = m.dirty[key] m.mu.RUnlock() return } -func (m *RWMutexMap) Store(key, value interface{}) { +func (m *RWMutexMap) Store(key, value any) { m.mu.Lock() if m.dirty == nil { - m.dirty = make(map[interface{}]interface{}) + m.dirty = make(map[any]any) } m.dirty[key] = value m.mu.Unlock() } -func (m *RWMutexMap) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) { +func (m *RWMutexMap) LoadOrStore(key, value any) (actual any, loaded bool) { m.mu.Lock() actual, loaded = m.dirty[key] if !loaded { actual = value if m.dirty == nil { - m.dirty = make(map[interface{}]interface{}) + m.dirty = make(map[any]any) } m.dirty[key] = value } @@ -57,7 +57,7 @@ func (m *RWMutexMap) LoadOrStore(key, value interface{}) (actual interface{}, lo return actual, loaded } -func (m *RWMutexMap) LoadAndDelete(key interface{}) (value interface{}, loaded bool) { +func (m *RWMutexMap) LoadAndDelete(key any) (value any, loaded bool) { m.mu.Lock() value, loaded = m.dirty[key] if !loaded { @@ -69,15 +69,15 @@ func (m *RWMutexMap) LoadAndDelete(key interface{}) (value interface{}, loaded b return value, loaded } -func (m *RWMutexMap) Delete(key interface{}) { +func (m *RWMutexMap) Delete(key any) { m.mu.Lock() delete(m.dirty, key) m.mu.Unlock() } -func (m *RWMutexMap) Range(f func(key, value interface{}) (shouldContinue bool)) { +func (m *RWMutexMap) Range(f func(key, value any) (shouldContinue bool)) { m.mu.RLock() - keys := make([]interface{}, 0, len(m.dirty)) + keys := make([]any, 0, len(m.dirty)) for k := range m.dirty { keys = append(keys, k) } @@ -102,13 +102,13 @@ type DeepCopyMap struct { clean atomic.Value } -func (m *DeepCopyMap) Load(key interface{}) (value interface{}, ok bool) { - clean, _ := m.clean.Load().(map[interface{}]interface{}) +func (m *DeepCopyMap) Load(key any) (value any, ok bool) { + clean, _ := m.clean.Load().(map[any]any) value, ok = clean[key] return value, ok } -func (m *DeepCopyMap) Store(key, value interface{}) { +func (m *DeepCopyMap) Store(key, value any) { m.mu.Lock() dirty := m.dirty() dirty[key] = value @@ -116,8 +116,8 @@ func (m *DeepCopyMap) Store(key, value interface{}) { m.mu.Unlock() } -func (m *DeepCopyMap) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) { - clean, _ := m.clean.Load().(map[interface{}]interface{}) +func (m *DeepCopyMap) LoadOrStore(key, value any) (actual any, loaded bool) { + clean, _ := m.clean.Load().(map[any]any) actual, loaded = clean[key] if loaded { return actual, loaded @@ -125,7 +125,7 @@ func (m *DeepCopyMap) LoadOrStore(key, value interface{}) (actual interface{}, l m.mu.Lock() // Reload clean in case it changed while we were waiting on m.mu. - clean, _ = m.clean.Load().(map[interface{}]interface{}) + clean, _ = m.clean.Load().(map[any]any) actual, loaded = clean[key] if !loaded { dirty := m.dirty() @@ -137,7 +137,7 @@ func (m *DeepCopyMap) LoadOrStore(key, value interface{}) (actual interface{}, l return actual, loaded } -func (m *DeepCopyMap) LoadAndDelete(key interface{}) (value interface{}, loaded bool) { +func (m *DeepCopyMap) LoadAndDelete(key any) (value any, loaded bool) { m.mu.Lock() dirty := m.dirty() value, loaded = dirty[key] @@ -147,7 +147,7 @@ func (m *DeepCopyMap) LoadAndDelete(key interface{}) (value interface{}, loaded return } -func (m *DeepCopyMap) Delete(key interface{}) { +func (m *DeepCopyMap) Delete(key any) { m.mu.Lock() dirty := m.dirty() delete(dirty, key) @@ -155,8 +155,8 @@ func (m *DeepCopyMap) Delete(key interface{}) { m.mu.Unlock() } -func (m *DeepCopyMap) Range(f func(key, value interface{}) (shouldContinue bool)) { - clean, _ := m.clean.Load().(map[interface{}]interface{}) +func (m *DeepCopyMap) Range(f func(key, value any) (shouldContinue bool)) { + clean, _ := m.clean.Load().(map[any]any) for k, v := range clean { if !f(k, v) { break @@ -164,9 +164,9 @@ func (m *DeepCopyMap) Range(f func(key, value interface{}) (shouldContinue bool) } } -func (m *DeepCopyMap) dirty() map[interface{}]interface{} { - clean, _ := m.clean.Load().(map[interface{}]interface{}) - dirty := make(map[interface{}]interface{}, len(clean)+1) +func (m *DeepCopyMap) dirty() map[any]any { + clean, _ := m.clean.Load().(map[any]any) + dirty := make(map[any]any, len(clean)+1) for k, v := range clean { dirty[k] = v } diff --git a/src/sync/map_test.go b/src/sync/map_test.go index c4a8f8b99aaa9..8352471104381 100644 --- a/src/sync/map_test.go +++ b/src/sync/map_test.go @@ -29,10 +29,10 @@ var mapOps = [...]mapOp{opLoad, opStore, opLoadOrStore, opLoadAndDelete, opDelet // mapCall is a quick.Generator for calls on mapInterface. type mapCall struct { op mapOp - k, v interface{} + k, v any } -func (c mapCall) apply(m mapInterface) (interface{}, bool) { +func (c mapCall) apply(m mapInterface) (any, bool) { switch c.op { case opLoad: return m.Load(c.k) @@ -52,11 +52,11 @@ func (c mapCall) apply(m mapInterface) (interface{}, bool) { } type mapResult struct { - value interface{} + value any ok bool } -func randValue(r *rand.Rand) interface{} { +func randValue(r *rand.Rand) any { b := make([]byte, r.Intn(4)) for i := range b { b[i] = 'a' + byte(rand.Intn(26)) @@ -73,14 +73,14 @@ func (mapCall) Generate(r *rand.Rand, size int) reflect.Value { return reflect.ValueOf(c) } -func applyCalls(m mapInterface, calls []mapCall) (results []mapResult, final map[interface{}]interface{}) { +func applyCalls(m mapInterface, calls []mapCall) (results []mapResult, final map[any]any) { for _, c := range calls { v, ok := c.apply(m) results = append(results, mapResult{v, ok}) } - final = make(map[interface{}]interface{}) - m.Range(func(k, v interface{}) bool { + final = make(map[any]any) + m.Range(func(k, v any) bool { final[k] = v return true }) @@ -88,15 +88,15 @@ func applyCalls(m mapInterface, calls []mapCall) (results []mapResult, final map return results, final } -func applyMap(calls []mapCall) ([]mapResult, map[interface{}]interface{}) { +func applyMap(calls []mapCall) ([]mapResult, map[any]any) { return applyCalls(new(sync.Map), calls) } -func applyRWMutexMap(calls []mapCall) ([]mapResult, map[interface{}]interface{}) { +func applyRWMutexMap(calls []mapCall) ([]mapResult, map[any]any) { return applyCalls(new(RWMutexMap), calls) } -func applyDeepCopyMap(calls []mapCall) ([]mapResult, map[interface{}]interface{}) { +func applyDeepCopyMap(calls []mapCall) ([]mapResult, map[any]any) { return applyCalls(new(DeepCopyMap), calls) } @@ -155,7 +155,7 @@ func TestConcurrentRange(t *testing.T) { for n := iters; n > 0; n-- { seen := make(map[int64]bool, mapSize) - m.Range(func(ki, vi interface{}) bool { + m.Range(func(ki, vi any) bool { k, v := ki.(int64), vi.(int64) if v%k != 0 { t.Fatalf("while Storing multiples of %v, Range saw value %v", k, v) @@ -201,8 +201,8 @@ func TestMapRangeNestedCall(t *testing.T) { // Issue 46399 for i, v := range [3]string{"hello", "world", "Go"} { m.Store(i, v) } - m.Range(func(key, value interface{}) bool { - m.Range(func(key, value interface{}) bool { + m.Range(func(key, value any) bool { + m.Range(func(key, value any) bool { // We should be able to load the key offered in the Range callback, // because there are no concurrent Delete involved in this tested map. if v, ok := m.Load(key); !ok || !reflect.DeepEqual(v, value) { @@ -236,7 +236,7 @@ func TestMapRangeNestedCall(t *testing.T) { // Issue 46399 // After a Range of Delete, all keys should be removed and any // further Range won't invoke the callback. Hence length remains 0. length := 0 - m.Range(func(key, value interface{}) bool { + m.Range(func(key, value any) bool { length++ return true }) diff --git a/src/sync/pool.go b/src/sync/pool.go index 9802f29d6f6d5..d1abb6a8b7161 100644 --- a/src/sync/pool.go +++ b/src/sync/pool.go @@ -53,13 +53,13 @@ type Pool struct { // New optionally specifies a function to generate // a value when Get would otherwise return nil. // It may not be changed concurrently with calls to Get. - New func() interface{} + New func() any } // Local per-P Pool appendix. type poolLocalInternal struct { - private interface{} // Can be used only by the respective P. - shared poolChain // Local P can pushHead/popHead; any P can popTail. + private any // Can be used only by the respective P. + shared poolChain // Local P can pushHead/popHead; any P can popTail. } type poolLocal struct { @@ -80,14 +80,14 @@ var poolRaceHash [128]uint64 // directly, for fear of conflicting with other synchronization on that address. // Instead, we hash the pointer to get an index into poolRaceHash. // See discussion on golang.org/cl/31589. -func poolRaceAddr(x interface{}) unsafe.Pointer { +func poolRaceAddr(x any) unsafe.Pointer { ptr := uintptr((*[2]unsafe.Pointer)(unsafe.Pointer(&x))[1]) h := uint32((uint64(uint32(ptr)) * 0x85ebca6b) >> 16) return unsafe.Pointer(&poolRaceHash[h%uint32(len(poolRaceHash))]) } // Put adds x to the pool. -func (p *Pool) Put(x interface{}) { +func (p *Pool) Put(x any) { if x == nil { return } @@ -121,7 +121,7 @@ func (p *Pool) Put(x interface{}) { // // If Get would otherwise return nil and p.New is non-nil, Get returns // the result of calling p.New. -func (p *Pool) Get() interface{} { +func (p *Pool) Get() any { if race.Enabled { race.Disable() } @@ -150,7 +150,7 @@ func (p *Pool) Get() interface{} { return x } -func (p *Pool) getSlow(pid int) interface{} { +func (p *Pool) getSlow(pid int) any { // See the comment in pin regarding ordering of the loads. size := runtime_LoadAcquintptr(&p.localSize) // load-acquire locals := p.local // load-consume diff --git a/src/sync/pool_test.go b/src/sync/pool_test.go index d991621624ca7..bb20043a54391 100644 --- a/src/sync/pool_test.go +++ b/src/sync/pool_test.go @@ -64,7 +64,7 @@ func TestPoolNew(t *testing.T) { i := 0 p := Pool{ - New: func() interface{} { + New: func() any { i++ return i }, @@ -143,7 +143,7 @@ func TestPoolStress(t *testing.T) { done := make(chan bool) for i := 0; i < P; i++ { go func() { - var v interface{} = 0 + var v any = 0 for j := 0; j < N; j++ { if v == nil { v = 0 @@ -290,7 +290,7 @@ func BenchmarkPoolStarvation(b *testing.B) { }) } -var globalSink interface{} +var globalSink any func BenchmarkPoolSTW(b *testing.B) { // Take control of GC. @@ -303,7 +303,7 @@ func BenchmarkPoolSTW(b *testing.B) { for i := 0; i < b.N; i++ { // Put a large number of items into a pool. const N = 100000 - var item interface{} = 42 + var item any = 42 for i := 0; i < N; i++ { p.Put(item) } @@ -338,7 +338,7 @@ func BenchmarkPoolExpensiveNew(b *testing.B) { // Create a pool that's "expensive" to fill. var p Pool var nNew uint64 - p.New = func() interface{} { + p.New = func() any { atomic.AddUint64(&nNew, 1) time.Sleep(time.Millisecond) return 42 @@ -348,7 +348,7 @@ func BenchmarkPoolExpensiveNew(b *testing.B) { b.RunParallel(func(pb *testing.PB) { // Simulate 100X the number of goroutines having items // checked out from the Pool simultaneously. - items := make([]interface{}, 100) + items := make([]any, 100) var sink []byte for pb.Next() { // Stress the pool. diff --git a/src/sync/poolqueue.go b/src/sync/poolqueue.go index 9be83e9a433ef..631f2c15fda26 100644 --- a/src/sync/poolqueue.go +++ b/src/sync/poolqueue.go @@ -77,7 +77,7 @@ func (d *poolDequeue) pack(head, tail uint32) uint64 { // pushHead adds val at the head of the queue. It returns false if the // queue is full. It must only be called by a single producer. -func (d *poolDequeue) pushHead(val interface{}) bool { +func (d *poolDequeue) pushHead(val any) bool { ptrs := atomic.LoadUint64(&d.headTail) head, tail := d.unpack(ptrs) if (tail+uint32(len(d.vals)))&(1<= 1 { // on Node.js 8, fs.utimes calls the callback without any arguments diff --git a/src/syscall/js/func.go b/src/syscall/js/func.go index 77fb9e66ca91f..cc9497236450b 100644 --- a/src/syscall/js/func.go +++ b/src/syscall/js/func.go @@ -10,7 +10,7 @@ import "sync" var ( funcsMu sync.Mutex - funcs = make(map[uint32]func(Value, []Value) interface{}) + funcs = make(map[uint32]func(Value, []Value) any) nextFuncID uint32 = 1 ) @@ -38,7 +38,7 @@ type Func struct { // new goroutine. // // Func.Release must be called to free up resources when the function will not be invoked any more. -func FuncOf(fn func(this Value, args []Value) interface{}) Func { +func FuncOf(fn func(this Value, args []Value) any) Func { funcsMu.Lock() id := nextFuncID nextFuncID++ diff --git a/src/syscall/js/js.go b/src/syscall/js/js.go index d80d5d63de2a5..a5210faf7fd26 100644 --- a/src/syscall/js/js.go +++ b/src/syscall/js/js.go @@ -148,7 +148,7 @@ func Global() Value { // | map[string]interface{} | new object | // // Panics if x is not one of the expected types. -func ValueOf(x interface{}) Value { +func ValueOf(x any) Value { switch x := x.(type) { case Value: return x @@ -192,13 +192,13 @@ func ValueOf(x interface{}) Value { return floatValue(x) case string: return makeValue(stringVal(x)) - case []interface{}: + case []any: a := arrayConstructor.New(len(x)) for i, s := range x { a.SetIndex(i, s) } return a - case map[string]interface{}: + case map[string]any: o := objectConstructor.New() for k, v := range x { o.Set(k, v) @@ -296,7 +296,7 @@ func valueGet(v ref, p string) ref // Set sets the JavaScript property p of value v to ValueOf(x). // It panics if v is not a JavaScript object. -func (v Value) Set(p string, x interface{}) { +func (v Value) Set(p string, x any) { if vType := v.Type(); !vType.isObject() { panic(&ValueError{"Value.Set", vType}) } @@ -335,7 +335,7 @@ func valueIndex(v ref, i int) ref // SetIndex sets the JavaScript index i of value v to ValueOf(x). // It panics if v is not a JavaScript object. -func (v Value) SetIndex(i int, x interface{}) { +func (v Value) SetIndex(i int, x any) { if vType := v.Type(); !vType.isObject() { panic(&ValueError{"Value.SetIndex", vType}) } @@ -347,7 +347,7 @@ func (v Value) SetIndex(i int, x interface{}) { func valueSetIndex(v ref, i int, x ref) -func makeArgs(args []interface{}) ([]Value, []ref) { +func makeArgs(args []any) ([]Value, []ref) { argVals := make([]Value, len(args)) argRefs := make([]ref, len(args)) for i, arg := range args { @@ -374,7 +374,7 @@ func valueLength(v ref) int // Call does a JavaScript call to the method m of value v with the given arguments. // It panics if v has no method m. // The arguments get mapped to JavaScript values according to the ValueOf function. -func (v Value) Call(m string, args ...interface{}) Value { +func (v Value) Call(m string, args ...any) Value { argVals, argRefs := makeArgs(args) res, ok := valueCall(v.ref, m, argRefs) runtime.KeepAlive(v) @@ -396,7 +396,7 @@ func valueCall(v ref, m string, args []ref) (ref, bool) // Invoke does a JavaScript call of the value v with the given arguments. // It panics if v is not a JavaScript function. // The arguments get mapped to JavaScript values according to the ValueOf function. -func (v Value) Invoke(args ...interface{}) Value { +func (v Value) Invoke(args ...any) Value { argVals, argRefs := makeArgs(args) res, ok := valueInvoke(v.ref, argRefs) runtime.KeepAlive(v) @@ -415,7 +415,7 @@ func valueInvoke(v ref, args []ref) (ref, bool) // New uses JavaScript's "new" operator with value v as constructor and the given arguments. // It panics if v is not a JavaScript function. // The arguments get mapped to JavaScript values according to the ValueOf function. -func (v Value) New(args ...interface{}) Value { +func (v Value) New(args ...any) Value { argVals, argRefs := makeArgs(args) res, ok := valueNew(v.ref, argRefs) runtime.KeepAlive(v) diff --git a/src/syscall/js/js_test.go b/src/syscall/js/js_test.go index fa8c782459c42..f860a5bb50581 100644 --- a/src/syscall/js/js_test.go +++ b/src/syscall/js/js_test.go @@ -364,8 +364,8 @@ func TestType(t *testing.T) { } } -type object = map[string]interface{} -type array = []interface{} +type object = map[string]any +type array = []any func TestValueOf(t *testing.T) { a := js.ValueOf(array{0, array{0, 42, 0}, 0}) @@ -388,7 +388,7 @@ func TestZeroValue(t *testing.T) { func TestFuncOf(t *testing.T) { c := make(chan struct{}) - cb := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + cb := js.FuncOf(func(this js.Value, args []js.Value) any { if got := args[0].Int(); got != 42 { t.Errorf("got %#v, want %#v", got, 42) } @@ -402,8 +402,8 @@ func TestFuncOf(t *testing.T) { func TestInvokeFunction(t *testing.T) { called := false - cb := js.FuncOf(func(this js.Value, args []js.Value) interface{} { - cb2 := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + cb := js.FuncOf(func(this js.Value, args []js.Value) any { + cb2 := js.FuncOf(func(this js.Value, args []js.Value) any { called = true return 42 }) @@ -423,7 +423,7 @@ func TestInterleavedFunctions(t *testing.T) { c1 := make(chan struct{}) c2 := make(chan struct{}) - js.Global().Get("setTimeout").Invoke(js.FuncOf(func(this js.Value, args []js.Value) interface{} { + js.Global().Get("setTimeout").Invoke(js.FuncOf(func(this js.Value, args []js.Value) any { c1 <- struct{}{} <-c2 return nil @@ -432,7 +432,7 @@ func TestInterleavedFunctions(t *testing.T) { <-c1 c2 <- struct{}{} // this goroutine is running, but the callback of setTimeout did not return yet, invoke another function now - f := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + f := js.FuncOf(func(this js.Value, args []js.Value) any { return nil }) f.Invoke() @@ -440,7 +440,7 @@ func TestInterleavedFunctions(t *testing.T) { func ExampleFuncOf() { var cb js.Func - cb = js.FuncOf(func(this js.Value, args []js.Value) interface{} { + cb = js.FuncOf(func(this js.Value, args []js.Value) any { fmt.Println("button clicked") cb.Release() // release the function if the button will not be clicked again return nil @@ -593,7 +593,7 @@ func BenchmarkDOM(b *testing.B) { } func TestGlobal(t *testing.T) { - ident := js.FuncOf(func(this js.Value, args []js.Value) interface{} { + ident := js.FuncOf(func(this js.Value, args []js.Value) any { return args[0] }) defer ident.Release() diff --git a/src/syscall/net_js.go b/src/syscall/net_js.go index 253ab22dd90c7..2ed4e191bd349 100644 --- a/src/syscall/net_js.go +++ b/src/syscall/net_js.go @@ -45,8 +45,7 @@ const ( SYS_FCNTL = 500 // unsupported ) -type Sockaddr interface { -} +type Sockaddr any type SockaddrInet4 struct { Port int diff --git a/src/syscall/syscall_windows.go b/src/syscall/syscall_windows.go index ecb1eeecf68c7..78e46a656d8dd 100644 --- a/src/syscall/syscall_windows.go +++ b/src/syscall/syscall_windows.go @@ -169,7 +169,7 @@ func (e Errno) Timeout() bool { } // Implemented in runtime/syscall_windows.go. -func compileCallback(fn interface{}, cleanstack bool) uintptr +func compileCallback(fn any, cleanstack bool) uintptr // NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention. // This is useful when interoperating with Windows code requiring callbacks. @@ -177,7 +177,7 @@ func compileCallback(fn interface{}, cleanstack bool) uintptr // Only a limited number of callbacks may be created in a single Go process, and any memory allocated // for these callbacks is never released. // Between NewCallback and NewCallbackCDecl, at least 1024 callbacks can always be created. -func NewCallback(fn interface{}) uintptr { +func NewCallback(fn any) uintptr { return compileCallback(fn, true) } @@ -187,7 +187,7 @@ func NewCallback(fn interface{}) uintptr { // Only a limited number of callbacks may be created in a single Go process, and any memory allocated // for these callbacks is never released. // Between NewCallback and NewCallbackCDecl, at least 1024 callbacks can always be created. -func NewCallbackCDecl(fn interface{}) uintptr { +func NewCallbackCDecl(fn any) uintptr { return compileCallback(fn, false) } diff --git a/src/testing/allocs_test.go b/src/testing/allocs_test.go index 5b346aaf83873..bbd3ae79c8531 100644 --- a/src/testing/allocs_test.go +++ b/src/testing/allocs_test.go @@ -6,7 +6,7 @@ package testing_test import "testing" -var global interface{} +var global any var allocsPerRunTests = []struct { name string diff --git a/src/testing/example.go b/src/testing/example.go index 0217c5d2425a6..f33e8d2f926e0 100644 --- a/src/testing/example.go +++ b/src/testing/example.go @@ -64,7 +64,7 @@ func sortLines(output string) string { // If recovered is non-nil, it'll panic with that value. // If the test panicked with nil, or invoked runtime.Goexit, it'll be // made to fail and panic with errNilPanicOrGoexit -func (eg *InternalExample) processRunResult(stdout string, timeSpent time.Duration, finished bool, recovered interface{}) (passed bool) { +func (eg *InternalExample) processRunResult(stdout string, timeSpent time.Duration, finished bool, recovered any) (passed bool) { passed = true dstr := fmtDuration(timeSpent) var fail string diff --git a/src/testing/fstest/mapfs.go b/src/testing/fstest/mapfs.go index 056ef133fac92..4595b7313db9d 100644 --- a/src/testing/fstest/mapfs.go +++ b/src/testing/fstest/mapfs.go @@ -37,7 +37,7 @@ type MapFile struct { Data []byte // file content Mode fs.FileMode // FileInfo.Mode ModTime time.Time // FileInfo.ModTime - Sys interface{} // FileInfo.Sys + Sys any // FileInfo.Sys } var _ fs.FS = MapFS(nil) @@ -156,7 +156,7 @@ func (i *mapFileInfo) Mode() fs.FileMode { return i.f.Mode } func (i *mapFileInfo) Type() fs.FileMode { return i.f.Mode.Type() } func (i *mapFileInfo) ModTime() time.Time { return i.f.ModTime } func (i *mapFileInfo) IsDir() bool { return i.f.Mode&fs.ModeDir != 0 } -func (i *mapFileInfo) Sys() interface{} { return i.f.Sys } +func (i *mapFileInfo) Sys() any { return i.f.Sys } func (i *mapFileInfo) Info() (fs.FileInfo, error) { return i, nil } // An openMapFile is a regular (non-directory) fs.File open for reading. diff --git a/src/testing/fstest/testfs.go b/src/testing/fstest/testfs.go index 5c4f30af16842..9a65fbbd0bb27 100644 --- a/src/testing/fstest/testfs.go +++ b/src/testing/fstest/testfs.go @@ -105,7 +105,7 @@ type fsTester struct { } // errorf adds an error line to errText. -func (t *fsTester) errorf(format string, args ...interface{}) { +func (t *fsTester) errorf(format string, args ...any) { if len(t.errText) > 0 { t.errText = append(t.errText, '\n') } diff --git a/src/testing/fuzz.go b/src/testing/fuzz.go index 19ff39947b643..18f2b2f319d9e 100644 --- a/src/testing/fuzz.go +++ b/src/testing/fuzz.go @@ -91,7 +91,7 @@ type corpusEntry = struct { Parent string Path string Data []byte - Values []interface{} + Values []any Generation int IsSeed bool } @@ -149,8 +149,8 @@ func (f *F) Skipped() bool { // Add will add the arguments to the seed corpus for the fuzz test. This will be // a no-op if called after or within the fuzz target, and args must match the // arguments for the fuzz target. -func (f *F) Add(args ...interface{}) { - var values []interface{} +func (f *F) Add(args ...any) { + var values []any for i := range args { if t := reflect.TypeOf(args[i]); !supportedTypes[t] { panic(fmt.Sprintf("testing: unsupported type to Add %v", t)) @@ -207,7 +207,7 @@ var supportedTypes = map[reflect.Type]bool{ // When fuzzing, F.Fuzz does not return until a problem is found, time runs out // (set with -fuzztime), or the test process is interrupted by a signal. F.Fuzz // should be called exactly once, unless F.Skip or F.Fail is called beforehand. -func (f *F) Fuzz(ff interface{}) { +func (f *F) Fuzz(ff any) { if f.fuzzCalled { panic("testing: F.Fuzz called more than once") } @@ -638,7 +638,7 @@ func fRunner(f *F, fn func(*F)) { // If we recovered a panic or inappropriate runtime.Goexit, fail the test, // flush the output log up to the root, then panic. - doPanic := func(err interface{}) { + doPanic := func(err any) { f.Fail() if r := f.runCleanup(recoverAndReturnPanic); r != nil { f.Logf("cleanup panicked with %v", r) diff --git a/src/testing/internal/testdeps/deps.go b/src/testing/internal/testdeps/deps.go index c612355a0070b..2e85a41b07751 100644 --- a/src/testing/internal/testdeps/deps.go +++ b/src/testing/internal/testdeps/deps.go @@ -186,7 +186,7 @@ func (TestDeps) ReadCorpus(dir string, types []reflect.Type) ([]fuzz.CorpusEntry return fuzz.ReadCorpus(dir, types) } -func (TestDeps) CheckCorpus(vals []interface{}, types []reflect.Type) error { +func (TestDeps) CheckCorpus(vals []any, types []reflect.Type) error { return fuzz.CheckCorpus(vals, types) } diff --git a/src/testing/quick/quick.go b/src/testing/quick/quick.go index 777338bb37de5..e73d307c13a7c 100644 --- a/src/testing/quick/quick.go +++ b/src/testing/quick/quick.go @@ -227,7 +227,7 @@ func (s SetupError) Error() string { return string(s) } // A CheckError is the result of Check finding an error. type CheckError struct { Count int - In []interface{} + In []any } func (s *CheckError) Error() string { @@ -237,8 +237,8 @@ func (s *CheckError) Error() string { // A CheckEqualError is the result CheckEqual finding an error. type CheckEqualError struct { CheckError - Out1 []interface{} - Out2 []interface{} + Out1 []any + Out2 []any } func (s *CheckEqualError) Error() string { @@ -260,7 +260,7 @@ func (s *CheckEqualError) Error() string { // t.Error(err) // } // } -func Check(f interface{}, config *Config) error { +func Check(f any, config *Config) error { if config == nil { config = &defaultConfig } @@ -299,7 +299,7 @@ func Check(f interface{}, config *Config) error { // It calls f and g repeatedly with arbitrary values for each argument. // If f and g return different answers, CheckEqual returns a *CheckEqualError // describing the input and the outputs. -func CheckEqual(f, g interface{}, config *Config) error { +func CheckEqual(f, g any, config *Config) error { if config == nil { config = &defaultConfig } @@ -358,7 +358,7 @@ func arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand return } -func functionAndType(f interface{}) (v reflect.Value, t reflect.Type, ok bool) { +func functionAndType(f any) (v reflect.Value, t reflect.Type, ok bool) { v = reflect.ValueOf(f) ok = v.Kind() == reflect.Func if !ok { @@ -368,15 +368,15 @@ func functionAndType(f interface{}) (v reflect.Value, t reflect.Type, ok bool) { return } -func toInterfaces(values []reflect.Value) []interface{} { - ret := make([]interface{}, len(values)) +func toInterfaces(values []reflect.Value) []any { + ret := make([]any, len(values)) for i, v := range values { ret[i] = v.Interface() } return ret } -func toString(interfaces []interface{}) string { +func toString(interfaces []any) string { s := make([]string, len(interfaces)) for i, v := range interfaces { s[i] = fmt.Sprintf("%#v", v) diff --git a/src/testing/testing.go b/src/testing/testing.go index e4b7aa30e5555..7bd13a850c0b3 100644 --- a/src/testing/testing.go +++ b/src/testing/testing.go @@ -453,7 +453,7 @@ func newChattyPrinter(w io.Writer) *chattyPrinter { // Updatef prints a message about the status of the named test to w. // // The formatted message must include the test name itself. -func (p *chattyPrinter) Updatef(testName, format string, args ...interface{}) { +func (p *chattyPrinter) Updatef(testName, format string, args ...any) { p.lastNameMu.Lock() defer p.lastNameMu.Unlock() @@ -467,7 +467,7 @@ func (p *chattyPrinter) Updatef(testName, format string, args ...interface{}) { // Printf prints a message, generated by the named test, that does not // necessarily mention that tests's name itself. -func (p *chattyPrinter) Printf(testName, format string, args ...interface{}) { +func (p *chattyPrinter) Printf(testName, format string, args ...any) { p.lastNameMu.Lock() defer p.lastNameMu.Unlock() @@ -680,7 +680,7 @@ func (c *common) decorate(s string, skip int) string { // flushToParent writes c.output to the parent after first writing the header // with the given format and arguments. -func (c *common) flushToParent(testName, format string, args ...interface{}) { +func (c *common) flushToParent(testName, format string, args ...any) { p := c.parent p.mu.Lock() defer p.mu.Unlock() @@ -743,21 +743,21 @@ func fmtDuration(d time.Duration) string { // TB is the interface common to T, B, and F. type TB interface { Cleanup(func()) - Error(args ...interface{}) - Errorf(format string, args ...interface{}) + Error(args ...any) + Errorf(format string, args ...any) Fail() FailNow() Failed() bool - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) + Fatal(args ...any) + Fatalf(format string, args ...any) Helper() - Log(args ...interface{}) - Logf(format string, args ...interface{}) + Log(args ...any) + Logf(format string, args ...any) Name() string Setenv(key, value string) - Skip(args ...interface{}) + Skip(args ...any) SkipNow() - Skipf(format string, args ...interface{}) + Skipf(format string, args ...any) Skipped() bool TempDir() string @@ -906,7 +906,7 @@ func (c *common) logDepth(s string, depth int) { // and records the text in the error log. For tests, the text will be printed only if // the test fails or the -test.v flag is set. For benchmarks, the text is always // printed to avoid having performance depend on the value of the -test.v flag. -func (c *common) Log(args ...interface{}) { +func (c *common) Log(args ...any) { c.checkFuzzFn("Log") c.log(fmt.Sprintln(args...)) } @@ -916,48 +916,48 @@ func (c *common) Log(args ...interface{}) { // tests, the text will be printed only if the test fails or the -test.v flag is // set. For benchmarks, the text is always printed to avoid having performance // depend on the value of the -test.v flag. -func (c *common) Logf(format string, args ...interface{}) { +func (c *common) Logf(format string, args ...any) { c.checkFuzzFn("Logf") c.log(fmt.Sprintf(format, args...)) } // Error is equivalent to Log followed by Fail. -func (c *common) Error(args ...interface{}) { +func (c *common) Error(args ...any) { c.checkFuzzFn("Error") c.log(fmt.Sprintln(args...)) c.Fail() } // Errorf is equivalent to Logf followed by Fail. -func (c *common) Errorf(format string, args ...interface{}) { +func (c *common) Errorf(format string, args ...any) { c.checkFuzzFn("Errorf") c.log(fmt.Sprintf(format, args...)) c.Fail() } // Fatal is equivalent to Log followed by FailNow. -func (c *common) Fatal(args ...interface{}) { +func (c *common) Fatal(args ...any) { c.checkFuzzFn("Fatal") c.log(fmt.Sprintln(args...)) c.FailNow() } // Fatalf is equivalent to Logf followed by FailNow. -func (c *common) Fatalf(format string, args ...interface{}) { +func (c *common) Fatalf(format string, args ...any) { c.checkFuzzFn("Fatalf") c.log(fmt.Sprintf(format, args...)) c.FailNow() } // Skip is equivalent to Log followed by SkipNow. -func (c *common) Skip(args ...interface{}) { +func (c *common) Skip(args ...any) { c.checkFuzzFn("Skip") c.log(fmt.Sprintln(args...)) c.SkipNow() } // Skipf is equivalent to Logf followed by SkipNow. -func (c *common) Skipf(format string, args ...interface{}) { +func (c *common) Skipf(format string, args ...any) { c.checkFuzzFn("Skipf") c.log(fmt.Sprintf(format, args...)) c.SkipNow() @@ -1141,7 +1141,7 @@ const ( // runCleanup is called at the end of the test. // If catchPanic is true, this will catch panics, and return the recovered // value if any. -func (c *common) runCleanup(ph panicHandling) (panicVal interface{}) { +func (c *common) runCleanup(ph panicHandling) (panicVal any) { if ph == recoverAndReturnPanic { defer func() { panicVal = recover() @@ -1340,7 +1340,7 @@ func tRunner(t *T, fn func(t *T)) { t.signal <- signal }() - doPanic := func(err interface{}) { + doPanic := func(err any) { t.Fail() if r := t.runCleanup(recoverAndReturnPanic); r != nil { t.Logf("cleanup panicked with %v", r) @@ -1554,9 +1554,9 @@ func (f matchStringOnly) RunFuzzWorker(func(corpusEntry) error) error { return e func (f matchStringOnly) ReadCorpus(string, []reflect.Type) ([]corpusEntry, error) { return nil, errMain } -func (f matchStringOnly) CheckCorpus([]interface{}, []reflect.Type) error { return nil } -func (f matchStringOnly) ResetCoverage() {} -func (f matchStringOnly) SnapshotCoverage() {} +func (f matchStringOnly) CheckCorpus([]any, []reflect.Type) error { return nil } +func (f matchStringOnly) ResetCoverage() {} +func (f matchStringOnly) SnapshotCoverage() {} // Main is an internal function, part of the implementation of the "go test" command. // It was exported because it is cross-package and predates "internal" packages. @@ -1602,7 +1602,7 @@ type testDeps interface { CoordinateFuzzing(time.Duration, int64, time.Duration, int64, int, []corpusEntry, []reflect.Type, string, string) error RunFuzzWorker(func(corpusEntry) error) error ReadCorpus(string, []reflect.Type) ([]corpusEntry, error) - CheckCorpus([]interface{}, []reflect.Type) error + CheckCorpus([]any, []reflect.Type) error ResetCoverage() SnapshotCoverage() } diff --git a/src/text/scanner/scanner.go b/src/text/scanner/scanner.go index c5fc4ff93b906..f1fbf9861d06b 100644 --- a/src/text/scanner/scanner.go +++ b/src/text/scanner/scanner.go @@ -340,7 +340,7 @@ func (s *Scanner) error(msg string) { fmt.Fprintf(os.Stderr, "%s: %s\n", pos, msg) } -func (s *Scanner) errorf(format string, args ...interface{}) { +func (s *Scanner) errorf(format string, args ...any) { s.error(fmt.Sprintf(format, args...)) } diff --git a/src/text/template/exec.go b/src/text/template/exec.go index c42cbb2ad3030..37984cf91a074 100644 --- a/src/text/template/exec.go +++ b/src/text/template/exec.go @@ -126,7 +126,7 @@ func (e ExecError) Unwrap() error { } // errorf records an ExecError and terminates processing. -func (s *state) errorf(format string, args ...interface{}) { +func (s *state) errorf(format string, args ...any) { name := doublePercent(s.tmpl.Name()) if s.node == nil { format = fmt.Sprintf("template: %s: %s", name, format) @@ -179,7 +179,7 @@ func errRecover(errp *error) { // the output writer. // A template may be executed safely in parallel, although if parallel // executions share a Writer the output may be interleaved. -func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error { +func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error { tmpl := t.Lookup(name) if tmpl == nil { return fmt.Errorf("template: no template %q associated with template %q", name, t.name) @@ -197,11 +197,11 @@ func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) // // If data is a reflect.Value, the template applies to the concrete // value that the reflect.Value holds, as in fmt.Print. -func (t *Template) Execute(wr io.Writer, data interface{}) error { +func (t *Template) Execute(wr io.Writer, data any) error { return t.execute(wr, data) } -func (t *Template) execute(wr io.Writer, data interface{}) (err error) { +func (t *Template) execute(wr io.Writer, data any) (err error) { defer errRecover(&err) value, ok := data.(reflect.Value) if !ok { @@ -311,7 +311,7 @@ func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse. // IsTrue reports whether the value is 'true', in the sense of not the zero of its type, // and whether the value has a meaningful truth value. This is the definition of // truth used by if and other such actions. -func IsTrue(val interface{}) (truth, ok bool) { +func IsTrue(val any) (truth, ok bool) { return isTrue(reflect.ValueOf(val)) } @@ -1023,7 +1023,7 @@ func (s *state) printValue(n parse.Node, v reflect.Value) { // printableValue returns the, possibly indirected, interface value inside v that // is best for a call to formatted printer. -func printableValue(v reflect.Value) (interface{}, bool) { +func printableValue(v reflect.Value) (any, bool) { if v.Kind() == reflect.Pointer { v, _ = indirect(v) // fmt.Fprint handles nil. } diff --git a/src/text/template/exec_test.go b/src/text/template/exec_test.go index 3c40aa901e19e..8c8143396dbef 100644 --- a/src/text/template/exec_test.go +++ b/src/text/template/exec_test.go @@ -46,7 +46,7 @@ type T struct { MSI map[string]int MSIone map[string]int // one element, for deterministic output MSIEmpty map[string]int - MXI map[interface{}]int + MXI map[any]int MII map[int]int MI32S map[int32]string MI64S map[int64]string @@ -56,11 +56,11 @@ type T struct { MUI8S map[uint8]string SMSI []map[string]int // Empty interfaces; used to see if we can dig inside one. - Empty0 interface{} // nil - Empty1 interface{} - Empty2 interface{} - Empty3 interface{} - Empty4 interface{} + Empty0 any // nil + Empty1 any + Empty2 any + Empty3 any + Empty4 any // Non-empty interfaces. NonEmptyInterface I NonEmptyInterfacePtS *I @@ -138,7 +138,7 @@ var tVal = &T{ SB: []bool{true, false}, MSI: map[string]int{"one": 1, "two": 2, "three": 3}, MSIone: map[string]int{"one": 1}, - MXI: map[interface{}]int{"one": 1}, + MXI: map[any]int{"one": 1}, MII: map[int]int{1: 1}, MI32S: map[int32]string{1: "one", 2: "two"}, MI64S: map[int64]string{2: "i642", 3: "i643"}, @@ -209,7 +209,7 @@ func (t *T) Method2(a uint16, b string) string { return fmt.Sprintf("Method2: %d %s", a, b) } -func (t *T) Method3(v interface{}) string { +func (t *T) Method3(v any) string { return fmt.Sprintf("Method3: %v", v) } @@ -249,7 +249,7 @@ func (u *U) TrueFalse(b bool) string { return "" } -func typeOf(arg interface{}) string { +func typeOf(arg any) string { return fmt.Sprintf("%T", arg) } @@ -257,7 +257,7 @@ type execTest struct { name string input string output string - data interface{} + data any ok bool } @@ -390,7 +390,7 @@ var execTests = []execTest{ {".VariadicFuncInt", "{{call .VariadicFuncInt 33 `he` `llo`}}", "33=", tVal, true}, {"if .BinaryFunc call", "{{ if .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{end}}", "[1=2]", tVal, true}, {"if not .BinaryFunc call", "{{ if not .BinaryFunc}}{{call .BinaryFunc `1` `2`}}{{else}}No{{end}}", "No", tVal, true}, - {"Interface Call", `{{stringer .S}}`, "foozle", map[string]interface{}{"S": bytes.NewBufferString("foozle")}, true}, + {"Interface Call", `{{stringer .S}}`, "foozle", map[string]any{"S": bytes.NewBufferString("foozle")}, true}, {".ErrFunc", "{{call .ErrFunc}}", "bla", tVal, true}, {"call nil", "{{call nil}}", "", tVal, false}, @@ -748,7 +748,7 @@ func add(args ...int) int { return sum } -func echo(arg interface{}) interface{} { +func echo(arg any) any { return arg } @@ -767,7 +767,7 @@ func stringer(s fmt.Stringer) string { return s.String() } -func mapOfThree() interface{} { +func mapOfThree() any { return map[string]int{"three": 3} } @@ -1468,7 +1468,7 @@ func TestBlock(t *testing.T) { func TestEvalFieldErrors(t *testing.T) { tests := []struct { name, src string - value interface{} + value any want string }{ { @@ -1611,7 +1611,7 @@ func TestInterfaceValues(t *testing.T) { for _, tt := range tests { tmpl := Must(New("tmpl").Parse(tt.text)) var buf bytes.Buffer - err := tmpl.Execute(&buf, map[string]interface{}{ + err := tmpl.Execute(&buf, map[string]any{ "PlusOne": func(n int) int { return n + 1 }, @@ -1640,7 +1640,7 @@ func TestInterfaceValues(t *testing.T) { // Check that panics during calls are recovered and returned as errors. func TestExecutePanicDuringCall(t *testing.T) { - funcs := map[string]interface{}{ + funcs := map[string]any{ "doPanic": func() string { panic("custom panic string") }, @@ -1648,7 +1648,7 @@ func TestExecutePanicDuringCall(t *testing.T) { tests := []struct { name string input string - data interface{} + data any wantErr string }{ { diff --git a/src/text/template/funcs.go b/src/text/template/funcs.go index 11e2e903c850d..dca5ed28db84f 100644 --- a/src/text/template/funcs.go +++ b/src/text/template/funcs.go @@ -31,7 +31,7 @@ import ( // apply to arguments of arbitrary type can use parameters of type interface{} or // of type reflect.Value. Similarly, functions meant to return a result of arbitrary // type can return interface{} or reflect.Value. -type FuncMap map[string]interface{} +type FuncMap map[string]any // builtins returns the FuncMap. // It is not a global variable so the linker can dead code eliminate @@ -627,7 +627,7 @@ func HTMLEscapeString(s string) string { // HTMLEscaper returns the escaped HTML equivalent of the textual // representation of its arguments. -func HTMLEscaper(args ...interface{}) string { +func HTMLEscaper(args ...any) string { return HTMLEscapeString(evalArgs(args)) } @@ -718,13 +718,13 @@ func jsIsSpecial(r rune) bool { // JSEscaper returns the escaped JavaScript equivalent of the textual // representation of its arguments. -func JSEscaper(args ...interface{}) string { +func JSEscaper(args ...any) string { return JSEscapeString(evalArgs(args)) } // URLQueryEscaper returns the escaped value of the textual representation of // its arguments in a form suitable for embedding in a URL query. -func URLQueryEscaper(args ...interface{}) string { +func URLQueryEscaper(args ...any) string { return url.QueryEscape(evalArgs(args)) } @@ -733,7 +733,7 @@ func URLQueryEscaper(args ...interface{}) string { // except that each argument is indirected (if a pointer), as required, // using the same rules as the default string evaluation during template // execution. -func evalArgs(args []interface{}) string { +func evalArgs(args []any) string { ok := false var s string // Fast path for simple common case. diff --git a/src/text/template/parse/lex.go b/src/text/template/parse/lex.go index 95e33771c0973..40d0411121b7c 100644 --- a/src/text/template/parse/lex.go +++ b/src/text/template/parse/lex.go @@ -190,7 +190,7 @@ func (l *lexer) acceptRun(valid string) { // errorf returns an error token and terminates the scan by passing // back a nil pointer that will be the next state, terminating l.nextItem. -func (l *lexer) errorf(format string, args ...interface{}) stateFn { +func (l *lexer) errorf(format string, args ...any) stateFn { l.items <- item{itemError, l.start, fmt.Sprintf(format, args...), l.startLine} return nil } diff --git a/src/text/template/parse/parse.go b/src/text/template/parse/parse.go index 64b29a2e169bd..b0cbe9dfc8b0c 100644 --- a/src/text/template/parse/parse.go +++ b/src/text/template/parse/parse.go @@ -24,7 +24,7 @@ type Tree struct { Mode Mode // parsing mode. text string // text parsed to create the template (or its parent) // Parsing only; cleared after parse. - funcs []map[string]interface{} + funcs []map[string]any lex *lexer token [3]item // three-token lookahead for parser. peekCount int @@ -59,7 +59,7 @@ func (t *Tree) Copy() *Tree { // templates described in the argument string. The top-level template will be // given the specified name. If an error is encountered, parsing stops and an // empty map is returned with the error. -func Parse(name, text, leftDelim, rightDelim string, funcs ...map[string]interface{}) (map[string]*Tree, error) { +func Parse(name, text, leftDelim, rightDelim string, funcs ...map[string]any) (map[string]*Tree, error) { treeSet := make(map[string]*Tree) t := New(name) t.text = text @@ -128,7 +128,7 @@ func (t *Tree) peekNonSpace() item { // Parsing. // New allocates a new parse tree with the given name. -func New(name string, funcs ...map[string]interface{}) *Tree { +func New(name string, funcs ...map[string]any) *Tree { return &Tree{ Name: name, funcs: funcs, @@ -158,7 +158,7 @@ func (t *Tree) ErrorContext(n Node) (location, context string) { } // errorf formats the error and terminates processing. -func (t *Tree) errorf(format string, args ...interface{}) { +func (t *Tree) errorf(format string, args ...any) { t.Root = nil format = fmt.Sprintf("template: %s:%d: %s", t.ParseName, t.token[0].line, format) panic(fmt.Errorf(format, args...)) @@ -218,7 +218,7 @@ func (t *Tree) recover(errp *error) { } // startParse initializes the parser, using the lexer. -func (t *Tree) startParse(funcs []map[string]interface{}, lex *lexer, treeSet map[string]*Tree) { +func (t *Tree) startParse(funcs []map[string]any, lex *lexer, treeSet map[string]*Tree) { t.Root = nil t.lex = lex t.vars = []string{"$"} @@ -240,7 +240,7 @@ func (t *Tree) stopParse() { // the template for execution. If either action delimiter string is empty, the // default ("{{" or "}}") is used. Embedded template definitions are added to // the treeSet map. -func (t *Tree) Parse(text, leftDelim, rightDelim string, treeSet map[string]*Tree, funcs ...map[string]interface{}) (tree *Tree, err error) { +func (t *Tree) Parse(text, leftDelim, rightDelim string, treeSet map[string]*Tree, funcs ...map[string]any) (tree *Tree, err error) { defer t.recover(&err) t.ParseName = t.Name emitComment := t.Mode&ParseComments != 0 diff --git a/src/text/template/parse/parse_test.go b/src/text/template/parse/parse_test.go index c3679a08decb4..0c4778c7b3b7f 100644 --- a/src/text/template/parse/parse_test.go +++ b/src/text/template/parse/parse_test.go @@ -318,7 +318,7 @@ var parseTests = []parseTest{ {"block definition", `{{block "foo"}}hello{{end}}`, hasError, ""}, } -var builtins = map[string]interface{}{ +var builtins = map[string]any{ "printf": fmt.Sprintf, "contains": strings.Contains, } diff --git a/src/time/internal_test.go b/src/time/internal_test.go index 2c75e449d3109..f0dddb7373500 100644 --- a/src/time/internal_test.go +++ b/src/time/internal_test.go @@ -31,7 +31,7 @@ func forceZipFileForTesting(zipOnly bool) { var Interrupt = interrupt var DaysIn = daysIn -func empty(arg interface{}, seq uintptr) {} +func empty(arg any, seq uintptr) {} // Test that a runtimeTimer with a period that would overflow when on // expiration does not throw or cause other timers to hang. diff --git a/src/time/sleep.go b/src/time/sleep.go index b467d1d589d1e..1ffaabec6749b 100644 --- a/src/time/sleep.go +++ b/src/time/sleep.go @@ -14,8 +14,8 @@ type runtimeTimer struct { pp uintptr when int64 period int64 - f func(interface{}, uintptr) // NOTE: must not be closure - arg interface{} + f func(any, uintptr) // NOTE: must not be closure + arg any seq uintptr nextwhen int64 status uint32 @@ -41,7 +41,7 @@ func when(d Duration) int64 { func startTimer(*runtimeTimer) func stopTimer(*runtimeTimer) bool func resetTimer(*runtimeTimer, int64) bool -func modTimer(t *runtimeTimer, when, period int64, f func(interface{}, uintptr), arg interface{}, seq uintptr) +func modTimer(t *runtimeTimer, when, period int64, f func(any, uintptr), arg any, seq uintptr) // The Timer type represents a single event. // When the Timer expires, the current time will be sent on C, @@ -140,7 +140,7 @@ func (t *Timer) Reset(d Duration) bool { } // sendTime does a non-blocking send of the current time on c. -func sendTime(c interface{}, seq uintptr) { +func sendTime(c any, seq uintptr) { select { case c.(chan Time) <- Now(): default: @@ -172,6 +172,6 @@ func AfterFunc(d Duration, f func()) *Timer { return t } -func goFunc(arg interface{}, seq uintptr) { +func goFunc(arg any, seq uintptr) { go arg.(func())() } diff --git a/src/time/tzdata/generate_zipdata.go b/src/time/tzdata/generate_zipdata.go index 4f40b51c7365e..653577cafaf14 100644 --- a/src/time/tzdata/generate_zipdata.go +++ b/src/time/tzdata/generate_zipdata.go @@ -71,7 +71,7 @@ func main() { } } -func die(format string, args ...interface{}) { +func die(format string, args ...any) { fmt.Fprintf(os.Stderr, format+"\n", args...) os.Exit(1) }