And then revert the bootstrap cmd directories and certain testdata.
And adjust tests as needed.
Not reverting the changes in std that are bootstrapped,
because some of those changes would appear in API docs,
and we want to use any consistently.
Instead, rewrite 'any' to 'interface{}' in cmd/dist for those directories
when preparing the bootstrap copy.
A few files changed as a result of running gofmt -w
not because of interface{} -> any but because they
hadn't been updated for the new //go:build lines.
Fixes #49884.
Change-Id: Ie8045cba995f65bd79c694ec77a1b3d1fe01bb09
Reviewed-on: https://go-review.googlesource.com/c/go/+/368254
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
Reviewed-by: Robert Griesemer <gri@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
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 {
wantLCnt int64
wantPCnt int64
}
- testFnc interface{} // testRead | testWriteTo | testRemaining
+ testFnc any // testRead | testWriteTo | testRemaining
)
type (
spd sparseDatas
size int64
}
- fileMaker interface{} // makeReg | makeSparse
+ fileMaker any // makeReg | makeSparse
)
vectors := []struct {
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.
testClose struct { // Close() == wantErr
wantErr error
}
- testFnc interface{} // testHeader | testWrite | testReadFrom | testClose
+ testFnc any // testHeader | testWrite | testReadFrom | testClose
)
vectors := []struct {
wantLCnt int64
wantPCnt int64
}
- testFnc interface{} // testWrite | testReadFrom | testRemaining
+ testFnc any // testWrite | testReadFrom | testRemaining
)
type (
sph sparseHoles
size int64
}
- fileMaker interface{} // makeReg | makeSparse
+ fileMaker any // makeReg | makeSparse
)
vectors := []struct {
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 {
}
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 }
// 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
// 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.
off int64
n int
want string
- wanterr interface{}
+ wanterr any
}{
{0, 10, "0123456789", nil},
{1, 10, "123456789", io.EOF},
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)
+//go:build !amd64
// +build !amd64
package p
var chanVar chan int
-var ifaceVar interface{} = 5
+var ifaceVar any = 5
var assertVar = ifaceVar.(int)
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}
}
{"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)}"},
}
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:
switch 3 {
}
check(LINE, 1)
- switch i := (interface{})(3).(int); i {
+ switch i := (any)(3).(int); i {
}
check(LINE, 1)
c := make(chan int)
"fmt"
"os"
"path/filepath"
+ "regexp"
"runtime"
"strings"
)
}
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 (") {
// 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...)))
}
return p
}
-func (pkg *Package) Printf(format string, args ...interface{}) {
+func (pkg *Package) Printf(format string, args ...any) {
fmt.Fprintf(&pkg.buf, format, args...)
}
// 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{
+//go:build ignore
// +build ignore
// Ignored package
// 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"}
}
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
}
// 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
}
// 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) {
// 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
// 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
}
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() + ">"
}
fixed := false
- walk(f, func(n interface{}) {
+ walk(f, func(n any) {
cl, ok := n.(*ast.CompositeLit)
if !ok {
return
}
fixed := false
- walk(f, func(n interface{}) {
+ walk(f, func(n any) {
cl, ok := n.(*ast.CompositeLit)
if !ok {
return
// 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
// 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) {
// 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:
}
// After is the real type checker.
- after := func(n interface{}) {
+ after := func(n any) {
if n == nil {
return
}
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)
}
// 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, " "))
// 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...)
}
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
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
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) {
// 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)
}
// 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))
+//go:build android
// +build android
package android
+//go:build linux
// +build linux
package android
+//go:build !android
// +build !android
package android
+//go:build illumos
// +build illumos
package illumos
+//go:build solaris
// +build solaris
package illumos
+//go:build !illumos
// +build !illumos
package illumos
-// +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
}
}
- 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()
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)
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))
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)]
})
}
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)
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)
// 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 != "" {
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)
// 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 ""
// 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...)}
}
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)
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 != "" {
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)
}
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}
// 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}
})
}
}
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 {
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.
// 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...)
}
// 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 {
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)
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)
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...)}
}
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}
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{
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.
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}
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}
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 {
// 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() {
err error
}
-func notExistErrorf(format string, args ...interface{}) error {
+func notExistErrorf(format string, args ...any) error {
return notExistError{fmt.Errorf(format, args...)}
}
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]}
// 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)
}
// 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()
// (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)
// 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)
// 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 {
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,
}
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 {
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()
}
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)
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
// 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] {
// 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")
}
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))
// 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
// 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
})
//
// 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)
}
//
// 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)
}
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 {
}
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)
})
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)")
}
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...)
}
// 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) {
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()
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))
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
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]
)
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)
// 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...))
}
// 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 := " ."
// 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")
// 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 == "" {
// 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 {
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...)
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 {
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" {
// 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
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 {
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) {
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.
}
// 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()
}
// 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.
var tmpdir string
-func fatalf(format string, args ...interface{}) {
+func fatalf(format string, args ...any) {
os.RemoveAll(tmpdir)
log.Fatalf(format, args...)
}
// 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.
// 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),
// 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...)
}
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")
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
// 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) {
}
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 {
var exitCode = 0
-func errorf(format string, args ...interface{}) {
+func errorf(format string, args ...any) {
log.Printf(format, args...)
exitCode = 1
}
}
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)
return false
}
-func (f *FakeFile) Sys() interface{} {
+func (f *FakeFile) Sys() any {
return nil
}
// 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"
</html>
`))
-func dief(msg string, args ...interface{}) {
+func dief(msg string, args ...any) {
fmt.Fprintf(os.Stderr, msg, args...)
os.Exit(1)
}
}
// 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
cname = colorLightGrey
}
}
- var arg interface{}
+ var arg any
if ev.Type == trace.EvProcStart {
type Arg struct {
ThreadID uint64
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]
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]
// 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.
// 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)
}
// 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)
// 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)
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))
}
list *List
// The value stored with this element.
- Value interface{}
+ Value any
}
// Next returns the next list element or nil.
}
// 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)
}
// 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
}
// 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)
}
// 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
}
// 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
}
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
}
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) {
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.
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.
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.
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})
}
}
// Iterate through the ring and print its contents
- r.Do(func(p interface{}) {
+ r.Do(func(p any) {
fmt.Println(p.(int))
})
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))
})
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))
})
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))
})
//
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 {
// 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 {
// iteration
n = 0
s := 0
- r.Do(func(p interface{}) {
+ r.Do(func(p any) {
n++
if p != nil {
s += p.(int)
// 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.
return nil
}
-func (*emptyCtx) Value(key interface{}) interface{} {
+func (*emptyCtx) Value(key any) any {
return nil
}
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
}
// 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")
}
// 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()
", 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:
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
}
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 (
}
}
-func recoveredValue(fn func()) (v interface{}) {
+func recoveredValue(fn func()) (v any) {
defer func() { v = recover() }()
fn()
return
// }
//
// 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.
//
//
// 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.
Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
}
-type DecrypterOpts interface{}
+type DecrypterOpts any
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)
},
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
}
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)
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)
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)
}
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
}
// 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
// outBufPool pools the record-sized scratch buffers used by writeRecordLocked.
var outBufPool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
return new([]byte)
},
}
// 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
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
log.Fatalf("Missing required --host parameter")
}
- var priv interface{}
+ var priv any
var err error
switch *ecdsaCurve {
case "":
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 */)
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.
certPath := tempFile(string(cert))
defer os.Remove(certPath)
- var key interface{} = testRSAPrivateKey
+ var key any = testRSAPrivateKey
if test.key != nil {
key = test.key
}
"time"
)
-var tests = []interface{}{
+var tests = []any{
&clientHelloMsg{},
&serverHelloMsg{},
&finishedMsg{},
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 {
}
c, s := localPipe(t)
- replyChan := make(chan interface{})
+ replyChan := make(chan any)
go func() {
cli := Client(c, testConfig)
cli.vers = clientHello.vers
}
c, s := localPipe(t)
- replyChan := make(chan interface{})
+ replyChan := make(chan any)
go func() {
cli := Client(c, testConfig)
cli.vers = clientHello.vers
return nil, nil, err
}
- connChan := make(chan interface{}, 1)
+ connChan := make(chan any, 1)
go func() {
tcpConn, err := l.Accept()
if err != nil {
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)
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:
// 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 {
// 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) {
// 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
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)
}
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
}
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
}
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
}
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
// 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 {
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{
// 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
SignatureAlgorithm SignatureAlgorithm
PublicKeyAlgorithm PublicKeyAlgorithm
- PublicKey interface{}
+ PublicKey any
Version int
SerialNumber *big.Int
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)
}
// 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) {
//
// 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")
//
// 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")
SignatureAlgorithm SignatureAlgorithm
PublicKeyAlgorithm PublicKeyAlgorithm
- PublicKey interface{}
+ PublicKey any
Subject pkix.Name
// 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")
}
}
-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 {
tests := []struct {
name string
- pub, priv interface{}
+ pub, priv any
checkSig bool
sigAlgo SignatureAlgorithm
}{
tests := []struct {
name string
- priv interface{}
+ priv any
cert *Certificate
}{
{"RSA CA", privRSA, certRSA},
tests := []struct {
name string
- priv interface{}
+ priv any
sigAlgo SignatureAlgorithm
}{
{"RSA", testPrivateKey, SHA256WithRSA},
// 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
// 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)
}
// 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:
}
*d = string(s)
return nil
- case *interface{}:
+ case *any:
if d == nil {
return errNilPtr
}
}
case nil:
switch d := dest.(type) {
- case *interface{}:
+ case *any:
if d == nil {
return errNilPtr
}
*d = bv.(bool)
}
return err
- case *interface{}:
+ case *any:
*d = src
return nil
}
return c
}
-func asString(src interface{}) string {
+func asString(src any) string {
switch v := src.(type) {
case string:
return v
)
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
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
scanf64 float64
scantime time.Time
scanptr *int64
- scaniface interface{}
+ scaniface any
)
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{}
}
}
-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))
}
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...)
}
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
type valueConverterTest struct {
c driver.ValueConverter
- in, out interface{}
+ in, out any
err string
}
func TestRawBytesAllocs(t *testing.T) {
var tests = []struct {
name string
- in interface{}
+ in any
want string
}{
{"uint64", uint64(12345678), "12345678"},
}
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)
}
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,
},
},
1: {
- args: []interface{}{nilValuerVPtr},
+ args: []any{nilValuerVPtr},
want: []driver.NamedValue{
{
Ordinal: 1,
},
},
2: {
- args: []interface{}{nilValuerPPtr},
+ args: []any{nilValuerPPtr},
want: []driver.NamedValue{
{
Ordinal: 1,
},
},
3: {
- args: []interface{}{"plain-str"},
+ args: []any{"plain-str"},
want: []driver.NamedValue{
{
Ordinal: 1,
},
},
4: {
- args: []interface{}{nilStrPtr},
+ args: []any{nilStrPtr},
want: []driver.NamedValue{
{
Ordinal: 1,
// 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 {
// 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.
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
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:
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
Converter ValueConverter
}
-func (n Null) ConvertValue(v interface{}) (Value, error) {
+func (n Null) ConvertValue(v any) (Value, error) {
if v == nil {
return nil, nil
}
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")
}
}
// 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
}
// IsScanValue is equivalent to IsValue.
// It exists for compatibility.
-func IsScanValue(v interface{}) bool {
+func IsScanValue(v any) bool {
return IsValue(v)
}
return vr.Value()
}
-func (defaultConverter) ConvertValue(v interface{}) (Value, error) {
+func (defaultConverter) ConvertValue(v any) (Value, error) {
if IsValue(v) {
return v, nil
}
type valueConverterTest struct {
c ValueConverter
- in interface{}
- out interface{}
+ in any
+ out any
err string
}
}
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 {
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)
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...))
}
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":
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 {
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
rows: [][]*row{
{
{
- cols: []interface{}{
+ cols: []any{
txStatus,
},
},
// 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 {
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]]
}
//
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
type anyTypeConverter struct{}
-func (anyTypeConverter) ConvertValue(v interface{}) (driver.Value, error) {
+func (anyTypeConverter) ConvertValue(v any) (driver.Value, error) {
return v, nil
}
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)
}
// 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.
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
}
// 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
// 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.
// 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
}
// 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.
// 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)
}
// 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 {
// 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
//
// 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
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)
}()
// 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
//
// 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
// 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 {
// 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}
}
//
// 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...)
}
// 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
// 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
// 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}
}
//
// 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
// 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
//
// 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
//
// 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...)
}
// 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}
}
//
// 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...)
}
// 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()
//
// 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()
// 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()
//
// 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)
// 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}
//
// 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...)
}
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)
//
// 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 {
// 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
}
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 {
}
types[i] = st
}
- values := make([]interface{}, len(tt))
+ values := make([]any, len(tt))
for i := range values {
values[i] = reflect.New(types[i]).Interface()
}
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...)
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)
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")
tests := []struct {
name string
- input interface{}
+ input any
expectedError string
}{
{
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
}
type nullTestRow struct {
- nullParam interface{}
- notNullParam interface{}
- scanNullVal interface{}
+ nullParam any
+ notNullParam any
+ scanNullVal any
}
type nullTestSpec struct {
t.Fatal("select", err)
}
- list := []struct{ got, want interface{} }{
+ list := []struct{ got, want any }{
{o1, "from-server"},
{dec1, decimalInt{123}},
{str1, "hello"},
var errTestScanWrap = errors.New("errTestScanWrap")
-func (alwaysErrScanner) Scan(interface{}) error {
+func (alwaysErrScanner) Scan(any) error {
return errTestScanWrap
}
// ClassUnknown.
type Field struct {
Attr Attr
- Val interface{}
+ Val any
Class Class
}
// 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
}
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))
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()
)
type nameTest struct {
- val interface{}
+ val any
str string
}
type FormatError struct {
off int64
msg string
- val interface{}
+ val any
}
func (e *FormatError) Error() string {
type DecodingError struct {
off int
msg string
- val interface{}
+ val any
}
func (e *DecodingError) Error() string {
type FormatError struct {
off int64
msg string
- val interface{}
+ val any
}
func (e *FormatError) Error() string {
type fileTest struct {
file string
hdr FileHeader
- loads []interface{}
+ loads []any
sections []*SectionHeader
relocations map[string][]Reloc
}
{
"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},
{
"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},
{
"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},
{
"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
{
"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
// 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)
// 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
// 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
}
type fileTest struct {
file string
hdr FileHeader
- opthdr interface{}
+ opthdr any
sections []*SectionHeader
symbols []*Symbol
hasNoDwarfInfo bool
},
}
-func isOptHdrEq(a, b interface{}) bool {
+func isOptHdrEq(a, b any) bool {
switch va := a.(type) {
case *OptionalHeader32:
vb, ok := b.(*OptionalHeader32)
type formatError struct {
off int
msg string
- val interface{}
+ val any
}
func (e *formatError) Error() string {
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 }
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] {
},
}
-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...)
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 {
//
// 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, "")
}
// 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)}
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}}},
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"},
type AttributeTypeAndValue struct {
Type ObjectIdentifier
- Value interface{}
+ Value any
}
type Validity struct {
}
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 {
// 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
var PST = time.FixedZone("PST", -8*60*60)
type marshalTest struct {
- in interface{}
+ in any
out string // hex encoded
}
}
type marshalWithParamsTest struct {
- in interface{}
+ in any
params string
out string // hex encoded
}
}
type marshalErrTest struct {
- in interface{}
+ in any
err string
}
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 {
return
}
- var v1 interface{}
+ var v1 any
_, err = Unmarshal(data1, &v1)
if err != nil {
t.Errorf("%v", err)
type testCase struct {
in []byte
- out interface{}
+ out any
}
var testData []testCase
for _, test := range unmarshalTestData {
"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...)
"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...)
// 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)
// 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)
// 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)))
}
// 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
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
}
}
-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)
}
// Addresses of arrays are easier to manipulate with reflection than are slices.
-var intArrays = []interface{}{
+var intArrays = []any{
&[100]int8{},
&[100]int16{},
&[100]int32{},
count := func() int {
var i int
- structSize.Range(func(_, _ interface{}) bool {
+ structSize.Range(func(_, _ any) bool {
i++
return true
})
}
testcases := []struct {
- val interface{}
+ val any
want int
}{
{new(foo), 1},
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 {
}
func testReadInvalidDestination(t *testing.T, order ByteOrder) {
- destinations := []interface{}{
+ destinations := []any{
int8(0),
int16(0),
int32(0),
func ExampleWrite_multi() {
buf := new(bytes.Buffer)
- var data = []interface{}{
+ var data = []any{
uint16(61374),
int8(-54),
uint8(254),
// 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) {
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.
}
}
-var singletons = []interface{}{
+var singletons = []any{
true,
7,
uint(10),
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
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 {
}
dec := NewDecoder(buf)
- var e interface{}
+ var e any
if err := dec.Decode(&e); err != nil {
return err
}
}
// all possible inputs
- input := []interface{}{
+ input := []any{
new(int),
new(float32),
new(float64),
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))
// 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
}
// 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{})
}
}
var encBufferPool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
e := new(encBuffer)
e.data = e.scratch[0:0]
return e
// 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))
}
// Test basic operations in a safe manner.
func TestBasicEncoderDecoder(t *testing.T) {
- var values = []interface{}{
+ var values = []any{
true,
int(123),
int8(123),
// 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)
}
// Types not supported at top level by the Encoder.
-var unsupportedValues = []interface{}{
+var unsupportedValues = []any{
make(chan int),
func(a int) bool { return true },
}
}
}
-func encAndDec(in, out interface{}) error {
+func encAndDec(in, out any) error {
b := new(bytes.Buffer)
enc := NewEncoder(b)
err := enc.Encode(in)
var testArray [7]int
type SingleTest struct {
- in interface{}
- out interface{}
+ in any
+ out any
err string
}
// encoder and decoder don't skew with respect to type definitions.
type Struct0 struct {
- I interface{}
+ I any
}
type NewType0 struct {
}
type ignoreTest struct {
- in, out interface{}
+ in, out any
}
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) {
// Another bug from golang-nuts, involving nested interfaces.
type Bug0Outer struct {
- Bug0Field interface{}
+ Bug0Field any
}
type Bug0Inner struct {
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)
}
func TestGobMapInterfaceEncode(t *testing.T) {
- m := map[string]interface{}{
+ m := map[string]any{
"up": uintptr(0),
"i0": []int{-1},
"i1": []int8{-1},
// 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)
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)
}
}
-func encodeAndRecover(value interface{}) (encodeErr, panicErr error) {
+func encodeAndRecover(value any) (encodeErr, panicErr error) {
defer func() {
e := recover()
if e != nil {
)
testCases := []struct {
- value interface{}
+ value any
mustPanic bool
}{
{nilStringPtr, true},
func TestNilPointerInsideInterface(t *testing.T) {
var ip *int
si := struct {
- I interface{}
+ I any
}{
I: ip,
}
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{}
}
return
}
- var dst []interface{}
+ var dst []any
err = NewDecoder(buf).Decode(&dst)
if err != nil {
t.Errorf("decode: %v", err)
}
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{
// 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...))
}
}
type isZeroBugInterface struct {
- I interface{}
+ I any
}
func (i isZeroBugInterface) GobEncode() (b []byte, e error) {
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 {
}
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()
}
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
}
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
}
}
}
-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
}
func BenchmarkEncodeInterfaceSlice(b *testing.B) {
- a := make([]interface{}, 1000)
+ a := make([]any, 1000)
for i := range a {
a[i] = "now is the time"
}
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)
}
func BenchmarkDecodeInterfaceSlice(b *testing.B) {
- a := make([]interface{}, 1000)
+ a := make([]any, 1000)
for i := range a {
a[i] = "now is the time"
}
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)
// 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 {
// 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")
// 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()
// See comment in type.go/Register.
func TestRegistrationNaming(t *testing.T) {
testCases := []struct {
- t interface{}
+ t any
name string
}{
{&N1{}, "*gob.N1"},
var buf bytes.Buffer
enc := NewEncoder(&buf)
dec := NewDecoder(&buf)
- var x interface{}
+ var x any
switch i {
case 0:
x = &N1{}
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)
}
// 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.
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)}
// 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)
// 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
}
// 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)
}
// 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)
}
// 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)
// 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()
}
type V struct {
- F1 interface{}
+ F1 any
F2 int32
F3 Number
F4 *VOuter
// 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 {
}
type XYZ struct {
- X interface{}
- Y interface{}
- Z interface{}
+ X any
+ Y any
+ Z any
}
type unexportedWithMethods struct{}
type unmarshalTest struct {
in string
- ptr interface{} // new(type)
- out interface{}
+ ptr any // new(type)
+ out any
err error
useNumber bool
golden bool
{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{}},
{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},
{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},
func TestUnmarshalMarshal(t *testing.T) {
initBig()
- var v interface{}
+ var v any
if err := Unmarshal(jsonBig, &v); err != nil {
t.Fatalf("Unmarshal: %v", err)
}
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)
}
PSmall *Small
PPSmall **Small
- Interface interface{}
- PInterface *interface{}
+ Interface any
+ PInterface *any
unexported int
}
}
var interfaceSetTests = []struct {
- pre interface{}
+ pre any
json string
- post interface{}
+ post any
}{
{"foo", `"bar"`, "bar"},
{"foo", `2`, 2.0},
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)
PBool *bool
Map map[string]string
Slice []string
- Interface interface{}
+ Interface any
PRaw *RawMessage
PTime *time.Time
}
var decodeTypeErrorTests = []struct {
- dest interface{}
+ dest any
src string
}{
{new(string), `{"user": "name"}`}, // issue 4628.
}
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 {
// 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:"-"`
}
// Issue 3717
func TestSkipArrayObjects(t *testing.T) {
json := `[{}]`
- var dest [0]interface{}
+ var dest [0]any
err := Unmarshal([]byte(json), &dest)
if err != nil {
// 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}`,
},
{
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]`,
}
var invalidUnmarshalTests = []struct {
- v interface{}
+ v any
want string
}{
{nil, "json: Unmarshal(nil)"},
}
var invalidUnmarshalTextTests = []struct {
- v interface{}
+ v any
want string
}{
{nil, "json: Unmarshal(nil)"},
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}
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.
dec := NewDecoder(strings.NewReader(tt.in))
var err error
for {
- var v interface{}
+ var v any
if err = dec.Decode(&v); err != nil {
break
}
// 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"}`)
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
},
// 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})
// 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
// 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
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.
// 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 {
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"`
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 {
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}
)
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
}
}
}
-var unsupportedValues = []interface{}{
+var unsupportedValues = []any{
math.NaN(),
math.Inf(-1),
math.Inf(1),
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 }
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 }
}, {
// 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 }
}, {
// Exported embedded field of non-struct type should be serialized.
label: "ExportedEmbeddedInt",
- makeInput: func() interface{} {
+ makeInput: func() any {
type (
MyInt int
S struct{ MyInt }
// 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 }
// 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 }
// 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 }
// 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 }
// 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
// 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 }
// 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 {
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
// Issue 13783
func TestEncodeBytekind(t *testing.T) {
testdata := []struct {
- data interface{}
+ data any
want string
}{
{byte(7), "7"},
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)
)
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},
// 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},
// 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},
}
for _, c := range colors {
- var dst interface{}
+ var dst any
switch c.Space {
case "RGB":
dst = new(RGB)
)
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)
}
var scannerPool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
return &scanner{}
},
}
jsonBig = b
}
-func genValue(n int) interface{} {
+func genValue(n int) any {
if n > 1 {
switch rand.Intn(2) {
case 0:
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
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
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)
}
//
// 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
}
//
// 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
}
// string, for JSON string literals
// nil, for JSON null
//
-type Token interface{}
+type Token any
const (
tokenTopValue = iota
if !dec.tokenValueAllowed() {
return dec.tokenError(c)
}
- var x interface{}
+ var x any
if err := dec.Decode(&x); err != nil {
return nil, err
}
// 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
}
for _, tt := range []struct {
name string
- v interface{}
+ v any
wantEscape string
want string
}{
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 {
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.
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},
}},
}
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 {
}
var structTagObjectKeyTests = []struct {
- raw interface{}
+ raw any
value string
key string
}{
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 {
// 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
// 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)
// 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
// 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
}
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
}
type Plain struct {
- V interface{}
+ V any
}
type MyInt int
CDATA string `xml:",cdata"`
}
-func ifaceptr(x interface{}) interface{} {
+func ifaceptr(x any) any {
return &x
}
type IfaceComment struct {
T1 T1
- Comment interface{} `xml:",comment"`
+ Comment any `xml:",comment"`
T2 T2
}
type IfaceChardata struct {
T1 T1
- Chardata interface{} `xml:",chardata"`
+ Chardata any `xml:",chardata"`
T2 T2
}
type IfaceCDATA struct {
T1 T1
- CDATA interface{} `xml:",cdata"`
+ CDATA any `xml:",cdata"`
T2 T2
}
type IfaceInnerXML struct {
T1 T1
- InnerXML interface{} `xml:",innerxml"`
+ InnerXML any `xml:",innerxml"`
T2 T2
}
type IfaceElement struct {
T1 T1
- Element interface{}
+ Element any
T2 T2
}
type IfaceOmitEmpty struct {
T1 T1
- OmitEmpty interface{} `xml:",omitempty"`
+ OmitEmpty any `xml:",omitempty"`
T2 T2
}
type IfaceAny struct {
T1 T1
- Any interface{} `xml:",any"`
+ Any any `xml:",any"`
T2 T2
}
// 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
}
var marshalErrorTests = []struct {
- Value interface{}
+ Value any
Err string
Kind reflect.Kind
}{
}
var marshalIndentTests = []struct {
- Value interface{}
+ Value any
Prefix string
Indent string
ExpectXML string
func TestStructPointerMarshal(t *testing.T) {
type A struct {
XMLName string `xml:"a"`
- B []interface{}
+ B []any
}
type C struct {
XMLName Name
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 {
// 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)
}
// 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")
}
// 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()
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"},
}
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"}},
}
type Pod struct {
- Pea interface{} `xml:"Pea"`
+ Pea any `xml:"Pea"`
}
// https://golang.org/issue/6836
// 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 {
//
// 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")
}
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)
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
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,
func TestAsValidation(t *testing.T) {
var s string
- testCases := []interface{}{
+ testCases := []any{
nil,
(*int)(nil),
"error",
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
})
// 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()
}
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
// 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.")
}
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)
}
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)) }
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)) }
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) }
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) }
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) }
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) }
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) }
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() }
// 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.
}
// 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
// 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)
// 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)
)
func TestFmtInterface(t *testing.T) {
- var i1 interface{}
+ var i1 any
i1 = "abc"
s := Sprintf("%s", i1)
if s != "abc" {
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[:]
)
}
type SI struct {
- I interface{}
+ I any
}
// P is a type with a String method with pointer receiver for testing %p.
var fmtTests = []struct {
fmt string
- val interface{}
+ val any
out string
}{
{"%d", 12345, "12345"},
// 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.
// Tests to check that not supported verbs generate an error string.
{"%☠", nil, "%!☠(<nil>)"},
- {"%☠", interface{}(nil), "%!☠(<nil>)"},
+ {"%☠", any(nil), "%!☠(<nil>)"},
{"%☠", int(0), "%!☠(int=0)"},
{"%☠", uint(0), "%!☠(uint=0)"},
{"%☠", []byte{0, 1}, "[%!☠(uint8=0) %!☠(uint8=1)]"},
{"%☠", 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{}, "<invalid reflect.Value>"},
{"%☠", map[float64]int{NaN: 1}, "map[%!☠(float64=NaN):%!☠(int=1)]"},
}
}
}
-type SE []interface{} // slice of empty; notational compactness.
+type SE []any // slice of empty; notational compactness.
var reorderTests = []struct {
fmt string
}
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)
}
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)
}
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()
}
}
-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"},
// PanicS is a type that panics in String.
type PanicS struct {
- message interface{}
+ message any
}
// Value receiver.
// PanicGo is a type that panics in GoString.
type PanicGo struct {
- message interface{}
+ message any
}
// Value receiver.
// PanicF is a type that panics in Format.
type PanicF struct {
- message interface{}
+ message any
}
// Value receiver.
var panictests = []struct {
fmt string
- in interface{}
+ in any
out string
}{
// String
{"%#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>"}, // nil pointer special case
{"%s", PanicF{io.ErrUnexpectedEOF}, "%!s(PANIC=Format method: unexpected EOF)"},
var formatterFlagTests = []struct {
in string
- val interface{}
+ val any
out string
}{
// scalar values with the (unused by fmt) 'a' verb.
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
}
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.
// 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)
// 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)
// 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)
// 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)
// 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)
// 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)
}
}
-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 "<nil>". The likeliest causes are a
// Stringer that fails to guard against nil or a nil pointer for a
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{}
}
// 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.
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].
}
}
-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
// 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(' ')
// 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...)
}
// 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...)
}
// 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...)
}
// 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...)
}
// 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)
// 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)
// 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)
}
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.
}
// 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.
}
// 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)
// 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
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
}
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), ""},
}},
}
-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)
}
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...)
var eofTests = []struct {
format string
- v interface{}
+ v any
}{
{"%s", &stringVal},
{"%q", &stringVal},
// 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
}
// 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)
}
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(". ")
}
// 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})
}
)
var tests = []struct {
- x interface{} // x is printed as s
+ x any // x is printed as s
s string
}{
// basic types
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...))
}
//
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.
// 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)
// *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)
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{
// 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)"))
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")
runtime.GOMAXPROCS(procs)
b := &B{
common: common{
- signal: make(chan interface{}),
+ signal: make(chan any),
},
benchmark: Benchmark,
}
func Benchmark(f func(b *B)) BenchmarkResult {
b := &B{
common: common{
- signal: make(chan interface{}),
+ signal: make(chan any),
},
benchmark: InternalBenchmark{"", f},
}
}
// 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()
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()
}
// 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()
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()
}
// 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()
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()
}
// 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()
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()
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()
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)
}
// 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()
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()
}
// 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()
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()
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.
// 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()
}
// 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)
}
t := &T{
common: common{
- signal: make(chan interface{}),
+ signal: make(chan any),
},
name: testName,
startParallel: startParallel,
// 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
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)
}
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...))
}
// 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)
}
// 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)
}
// 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()
}
// 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)
}
// 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)
}
// 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)
}
// 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)
}
// 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)
}
// 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")
}
// 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)
//
// 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
// 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
}
// 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
{"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)}"},
"sync"
)
-func errorf(format string, args ...interface{}) {
+func errorf(format string, args ...any) {
panic(fmt.Sprintf(format, args...))
}
_ *T10
}
T11 map[int]string
- T12 interface{}
+ T12 any
T13 interface {
m1()
m2(int) float32
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 }
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()
}
}
-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 {
// 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:
// 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)")
}
// 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)")
}
// ----------------------------------------------------------------------------
// 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)
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:
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)
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...)
// 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
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 {
}
// 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)
// 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
}
// 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))
}
// 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)
}
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 != "_" {
// ----------------------------------------------------------------------------
// Parsing support
-func (p *parser) printTrace(a ...interface{}) {
+func (p *parser) printTrace(a ...any) {
const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " +
". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
const n = uint(len(dots))
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...))
}
}
// 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
}
// 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()
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 {
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 {
// 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}
}
type actionDesc struct {
pos positioner
format string
- args []interface{}
+ args []any
}
// A Checker maintains the state of the type checker.
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 != "" {
}
}
-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:
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),
}
// 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...))
}
}
// 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)
}
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...)
}
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 */
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")
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 {
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)
}
// 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)
}
bytes.Buffer
}
-func (g *gen) p(format string, args ...interface{}) {
+func (g *gen) p(format string, args ...any) {
fmt.Fprintf(&g.Buffer, format, args...)
}
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
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...))
}
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 != "" {
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},
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)
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) {
}
// 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
// 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
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...)
}
}
// 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
}
// 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
}
// 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:
)
func TestTypedContent(t *testing.T) {
- data := []interface{}{
+ data := []any{
`<b> "foo%" O'Reilly &bar;`,
CSS(`a[href =~ "//example.com"]#foo`),
HTML(`Hello, <b>World</b> &tc!`),
// 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()) {
}
// cssEscaper escapes HTML and CSS special characters using \<hex>+ 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
// (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
// 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...)}
}
// 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 {
// 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...)
}
// 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...)
}
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,
// 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
}
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" +
` !"#$%&'()*+,-./` +
}
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 {
func Example_escape() {
const s = `"Fran & Freddie's Diner" <tasty@example.com>`
- v := []interface{}{`"Fran & Freddie's Diner"`, ' ', `<tasty@example.com>`}
+ v := []any{`"Fran & Freddie's Diner"`, ' ', `<tasty@example.com>`}
fmt.Println(template.HTMLEscapeString(s))
template.HTMLEscape(os.Stdout, []byte(s))
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
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
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"},
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)
}
return ""
}
-func typeOf(arg interface{}) string {
+func typeOf(arg any) string {
return fmt.Sprintf("%T", arg)
}
name string
input string
output string
- data interface{}
+ data any
ok bool
}
{".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},
return sum
}
-func echo(arg interface{}) interface{} {
+func echo(arg any) any {
return arg
}
return s.String()
}
-func mapOfThree() interface{} {
+func mapOfThree() any {
return map[string]int{"three": 3}
}
func TestEvalFieldErrors(t *testing.T) {
tests := []struct {
name, src string
- value interface{}
+ value any
want string
}{
{
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
},
// 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")
},
tests := []struct {
name string
input string
- data interface{}
+ data any
wantErr string
}{
{
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
},
)
// 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)
}
// 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)
}
// 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)
}
// 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
// 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
// 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 ""
}
// 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
// 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) {
// jsStrEscaper produces a string that can be included between quotes in
// JavaScript source, in JavaScript embedded in an HTML5 <script> element,
// or in an HTML5 event handler attribute such as onclick.
-func jsStrEscaper(args ...interface{}) string {
+func jsStrEscaper(args ...any) string {
s, t := stringify(args...)
if t == contentTypeJSStr {
return replace(s, jsStrNormReplacementTable)
// specials so the result is treated literally when included in a regular
// expression literal. /foo{{.X}}bar/ matches the string "foo" followed by
// the literal text of {{.X}} followed by the string "bar".
-func jsRegexpEscaper(args ...interface{}) string {
+func jsRegexpEscaper(args ...any) string {
s, _ := stringify(args...)
s = replace(s, jsRegexpReplacementTable)
if s == "" {
func TestJSValEscaper(t *testing.T) {
tests := []struct {
- x interface{}
+ x any
js string
}{
{int(42), " 42 "},
// "\v" == "v" on IE 6 so use "\u000b" instead.
{"\t\x0b", `"\t\u000b"`},
{struct{ X, Y int }{1, 2}, `{"X":1,"Y":2}`},
- {[]interface{}{}, "[]"},
- {[]interface{}{42, "foo", nil}, `[42,"foo",null]`},
+ {[]any{}, "[]"},
+ {[]any{42, "foo", nil}, `[42,"foo",null]`},
{[]string{"<!--", "</script>", "-->"}, `["\u003c!--","\u003c/script\u003e","--\u003e"]`},
{"<!--", `"\u003c!--"`},
{"-->", `"--\u003e"`},
}
// 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)
func TestJSStrEscaper(t *testing.T) {
tests := []struct {
- x interface{}
+ x any
esc string
}{
{"", ``},
func TestJSRegexpEscaper(t *testing.T) {
tests := []struct {
- x interface{}
+ x any
esc string
}{
{"", `(?:)`},
tests := []struct {
name string
- escaper func(...interface{}) string
+ escaper func(...any) string
escaped string
}{
{
// 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
}
// 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
// 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.
// 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)
}
}
}
-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 {
// 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
// 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...)
}
// 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
// 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:
tests := []struct {
name string
- escaper func(...interface{}) string
+ escaper func(...any) string
escaped string
}{
{
}
func init() {
- var p interface{} = (*slowestRGBA)(nil)
+ var p any = (*slowestRGBA)(nil)
if _, ok := p.(RGBA64Image); ok {
panic("slowestRGBA should not be an RGBA64Image")
}
}
func init() {
- var p interface{} = (*slowerRGBA)(nil)
+ var p any = (*slowerRGBA)(nil)
if _, ok := p.(RGBA64Image); !ok {
panic("slowerRGBA should be an RGBA64Image")
}
// 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.
// the behavior is undefined.
//
// Implemented as a compile intrinsic.
-func FuncPCABIInternal(f interface{}) uintptr
+func FuncPCABIInternal(f any) uintptr
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)
}
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{
},
}
-func sprint(data interface{}) string {
+func sprint(data any) string {
om := fmtsort.Sort(reflect.ValueOf(data))
if om == nil {
return "nil"
// 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: "",
// 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")
}
}
// 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")
}
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 {
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 {
}
// 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)
}
// 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)
Data []byte
// Values is the unmarshaled values from a corpus file.
- Values []interface{}
+ Values []any
Generation int
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))
}
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))
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)
// 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))
}
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
panic(fmt.Sprintf("unsupported type: %v", t))
}
-var zeroVals []interface{} = []interface{}{
+var zeroVals []any = []any{
[]byte(""),
string(""),
false,
type testcase struct {
name string
fn func(CorpusEntry) error
- input []interface{}
- expected []interface{}
+ input []any
+ expected []any
}
cases := []testcase{
{
}
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",
}
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",
}
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",
}
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",
}
return nil
},
- input: []interface{}{"001010001000000000000000000"},
- expected: []interface{}{"111"},
+ input: []any{"001010001000000000000000000"},
+ expected: []any{"111"},
},
{
name: "string_length",
}
return nil
},
- input: []interface{}{"zzzzz"},
- expected: []interface{}{"00000"},
+ input: []any{"zzzzz"},
+ expected: []any{"00000"},
},
{
name: "string_with_letter",
}
return nil
},
- input: []interface{}{"ZZZZZ"},
- expected: []interface{}{"A"},
+ input: []any{"ZZZZZ"},
+ expected: []any{"A"},
},
}
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 {
}
// 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.
// 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)
}
})
}
// 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)
}
})
}
os.Setenv("GODEBUG", fmt.Sprintf("%s,fuzzseed=123", origEnv))
m := newMutator()
- types := []interface{}{
+ types := []any{
[]byte(""),
string(""),
false,
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)
// 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
}
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]
q.head = 0
}
-func (q *queue) enqueue(e interface{}) {
+func (q *queue) enqueue(e any) {
if q.len+1 > q.cap() {
q.grow()
}
q.len++
}
-func (q *queue) dequeue() (interface{}, bool) {
+func (q *queue) dequeue() (any, bool) {
if q.len == 0 {
return nil, false
}
return e, true
}
-func (q *queue) peek() (interface{}, bool) {
+func (q *queue) peek() (any, bool) {
if q.len == 0 {
return nil, false
}
}
}
- var resp interface{}
+ var resp any
switch {
case c.Fuzz != nil:
resp = ws.fuzz(ctx, *c.Fuzz)
resp.InternalErr = err.Error()
return resp
}
- vals := make([]interface{}, len(originalVals))
+ vals := make([]any, len(originalVals))
copy(vals, originalVals)
shouldStop := func() bool {
// 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
return true, retErr
}
-func writeToMem(vals []interface{}, mem *sharedMem) {
+func writeToMem(vals []any, mem *sharedMem) {
b := marshalCorpusFile(vals...)
mem.setValue(b)
}
// 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 {
}
}()
- initialVal := []interface{}{make([]byte, 32)}
+ initialVal := []any{make([]byte, 32)}
encodedVals := marshalCorpusFile(initialVal...)
mem.setValue(encodedVals)
}
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{
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)
// 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
// 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}
}
//
// 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))
}
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)
}
// 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)
// 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()
// 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
})
}
type pair struct {
- i interface{}
+ i any
s string
}
func TestInterfaceValue(t *testing.T) {
var inter struct {
- E interface{}
+ E any
}
inter.E = 123.456
v1 := ValueOf(&inter)
}
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")
type NotBasic Basic
type DeepEqualTest struct {
- a, b interface{}
+ a, b any
eq bool
}
type self struct{}
type Loop *Loop
-type Loopy interface{}
+type Loopy any
var loop1, loop2 Loop
var loopy1, loopy2 Loopy
{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},
}
}
-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()))
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 }{},
NotNil(mi, t)
var ii struct {
- x interface{}
+ x any
}
Nil(ii, t)
ii.x = 2
{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)), ""},
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
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 {
type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
type nameTest struct {
- v interface{}
+ v any
want string
}
{(*func() D1)(nil), ""},
{(*<-chan D1)(nil), ""},
{(*chan<- D1)(nil), ""},
- {(*interface{})(nil), ""},
+ {(*any)(nil), ""},
{(*interface {
F()
})(nil), ""},
// 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)
}
}
var implementsTests = []struct {
- x interface{}
- t interface{}
+ x any
+ t any
b bool
}{
{new(*bytes.Buffer), new(io.Reader), true},
}
var assignableTests = []struct {
- x interface{}
- t interface{}
+ x any
+ t any
b bool
}{
{new(chan int), new(<-chan int), true},
{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...) {
// 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()})
// 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)
}
}
// 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 {
}
// 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
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))
}
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})
}
// 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()
// 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{}
}
}
x := valueInterface(v)
if dst.NumMethod() == 0 {
- *(*interface{})(target) = x
+ *(*any)(target) = x
} else {
ifaceE2I(dst, x, target)
}
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
// 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
}
var dummy struct {
b bool
- x interface{}
+ x any
}
// 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
// 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
}
// 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)
// 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 {
}
// 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()
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 {
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 {
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()
type ValueTest struct {
Type uint32
Name string
- Value interface{}
+ Value any
WillFail bool
}
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
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
})
}
-func testHeaderMatchesReflect(t *testing.T, header, reflectHeader interface{}) {
+func testHeaderMatchesReflect(t *testing.T, header, reflectHeader any) {
h := reflect.TypeOf(header)
rh := reflect.TypeOf(reflectHeader)
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.
}
var blackHolePool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
b := make([]byte, 8192)
return &b
},
// 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
}
// 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
}
// 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
}
}
// 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)
// 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
}
// 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
}
// 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
}
}
// 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)
// https://golang.org/issue/201
type floatTest struct {
- val interface{}
+ val any
name string
str string
}
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
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} {
// 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)
}
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)
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))
}
}
-var regressGolden = []interface{}{
+var regressGolden = []any{
float64(4.668112973579268), // ExpFloat64()
float64(0.1601593871172866), // ExpFloat64()
float64(3.0465834105636), // ExpFloat64()
func TestReader(t *testing.T) {
tests := []struct {
in, want string
- err interface{}
+ err any
}{
{in: "", want: ""},
{in: "foo bar", want: "foo bar"},
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')
)
func clearSyncMap(m *sync.Map) {
- m.Range(func(k, _ interface{}) bool {
+ m.Range(func(k, _ any) bool {
m.Delete(k)
return true
})
}
}
-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 {
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...)
}
}
-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)
}
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 {
func TestH12_AutoGzip_Disabled(t *testing.T) {
h12Compare{
- Opts: []interface{}{
+ Opts: []any{
func(tr *Transport) { tr.DisableCompression = true },
},
Handler: func(w ResponseWriter, r *Request) {
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)
}))
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
// 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)
}
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)) }
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) }},
}
)
// frame header bytes.
// Used only by ReadFrameHeader.
var http2fhBytes = sync.Pool{
- New: func() interface{} {
+ New: func() any {
buf := make([]byte, http2frameHeaderLen)
return &buf
},
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)
}
}
var http2littleBuf = sync.Pool{
- New: func() interface{} {
+ New: func() any {
buf := make([]byte, 64)
return &buf
},
const http2bufWriterPoolBufferSize = 4 << 10
var http2bufWriterPool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
return bufio.NewWriterSize(nil, http2bufWriterPoolBufferSize)
},
}
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
)
var http2responseWriterStatePool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
rws := &http2responseWriterState{}
rws.bw = bufio.NewWriterSize(http2chunkWriter{rws}, http2handlerChunkWriteSize)
return rws
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.
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{}),
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
}
}
-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 {
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
}
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:
}
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
// 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
}
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...)
}
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
}
}
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)
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
}
}
-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 {
type http2Transport struct {
MaxHeaderListSize uint32
- ConnPool interface{}
+ ConnPool any
}
func (*http2Transport) RoundTrip(*Request) (*Response, error) { panic(noHTTP2) }
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) }
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
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) {
}
}
-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()
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"
}
}
}
- version := func(s string, wantErr interface{}) testCase {
+ version := func(s string, wantErr any) testCase {
if wantErr == true {
wantErr = "malformed HTTP version"
}
}
}
- 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),
// 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
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()
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())
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
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
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())
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.
// 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
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" +
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
// 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)
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:
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)
}))
// 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
}
)
var copyBufPool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
b := make([]byte, 32*1024)
return &b
},
// 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 {
// 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...)
h: make(Header),
req: r,
}
- panicChan := make(chan interface{}, 1)
+ panicChan := make(chan any, 1)
go func() {
defer func() {
if p := recover(); p != nil {
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
}
// 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
// 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
// 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...)
}
}
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...)
}
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...)
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...)
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...)
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...)
{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()
}
return true
}
-func checkFirstListener(network string, ln interface{}) error {
+func checkFirstListener(network string, ln any) error {
switch network {
case "tcp":
fd := ln.(*TCPListener).fd
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
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)
})
// 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
}
}
// 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
}
defer func() { testHookLookupIP = origTestHookLookupIP }()
keyValues := []struct {
- key, value interface{}
+ key, value any
}{
{"key-1", 12},
{384, "value2"},
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)
}
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...)
}
flags2 byte
flags3 byte
flags4 byte
- ipv6 interface{}
+ ipv6 any
}
func newip4i_v4(a, b, c, d byte) ip4i {
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.
// 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.
// 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
}
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
}
return c.dec.Decode(r)
}
-func (c *gobClientCodec) ReadResponseBody(body interface{}) error {
+func (c *gobClientCodec) ReadResponseBody(body any) error {
return c.dec.Decode(body)
}
// 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
}
// 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
}
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")
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 {
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 {
}
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()
type clientResponse struct {
Id uint64 `json:"id"`
Result *json.RawMessage `json:"result"`
- Error interface{} `json:"error"`
+ Error any `json:"error"`
}
func (r *clientResponse) reset() {
return nil
}
-func (c *clientCodec) ReadResponseBody(x interface{}) error {
+func (c *clientCodec) ReadResponseBody(x any) error {
if x == nil {
return nil
}
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 {
return nil
}
-func (c *serverCodec) ReadRequestBody(x interface{}) error {
+func (c *serverCodec) ReadRequestBody(x any) error {
if x == nil {
return nil
}
// 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 {
// 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)
}
// 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)
// 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
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,
}
// 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)
}
// 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
return nil
}
-func (codec *CodecEmulator) ReadRequestBody(argv interface{}) error {
+func (codec *CodecEmulator) ReadRequestBody(argv any) error {
if codec.args == nil {
return io.ErrUnexpectedEOF
}
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 {
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")
}
select {}
}
-func (WriteFailCodec) ReadResponseBody(interface{}) error {
+func (WriteFailCodec) ReadResponseBody(any) error {
select {}
}
}
// 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
// }
// 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...)
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)
// 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)
// 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 {
)
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
}
}
-var global interface{}
+var global any
func BenchmarkExpand(b *testing.B) {
b.Run("noop", func(b *testing.B) {
// 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()
}
// 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()
}
// 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()
}()
cmd, args := args[0], args[1:]
switch cmd {
case "echo":
- iargs := []interface{}{}
+ iargs := []any{}
for _, s := range args {
iargs = append(iargs, s)
}
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
}
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
}
}
// 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
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)
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
}
// 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,
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
//
// 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.
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
}
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
}
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.
// }
// *v.(*int) = 7
// f.(func())() // prints "Hello, number 7"
-type Symbol interface{}
+type Symbol any
}
// 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 {
)
// 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
// 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()
})
}
-var abiCallTestCases = []interface{}{
+var abiCallTestCases = []any{
passNone,
passInt,
passInt8,
return a, b, c
}
-var abiMakeFuncTestCases = []interface{}{
+var abiMakeFuncTestCases = []any{
callArgsNone,
callArgsInt,
callArgsInt8,
"unsafe"
)
-var sink interface{}
+var sink any
func TestBool(t *testing.T) {
v := ValueOf(true)
}
type pair struct {
- i interface{}
+ i any
s string
}
}
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
}
var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"}
var testCases = []struct {
- i interface{}
+ i any
want [4]bool
}{
// signed integer
func TestInterfaceGet(t *testing.T) {
var inter struct {
- E interface{}
+ E any
}
inter.E = 123.456
v1 := ValueOf(&inter)
func TestInterfaceValue(t *testing.T) {
var inter struct {
- E interface{}
+ E any
}
inter.E = 123.456
v1 := ValueOf(&inter)
}
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")
type NotBasic Basic
type DeepEqualTest struct {
- a, b interface{}
+ a, b any
eq bool
}
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
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
}
{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},
}
var deepEqualPerfTests = []struct {
- x, y interface{}
+ x, y any
}{
{x: int8(99), y: int8(99)},
{x: []int8{99}, y: []int8{99}},
}
}
-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 {
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())
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 }{},
NotNil(mi, t)
var ii struct {
- x interface{}
+ x any
}
Nil(ii, t)
ii.x = 2
func TestIsZero(t *testing.T) {
for i, tt := range []struct {
- x interface{}
+ x any
want bool
}{
// Booleans
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)
}
}
// 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()
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)
p := &Point{3, 4}
var s struct {
- I interface{}
+ I any
P interface {
Dist(int) int
}
}
type FTest struct {
- s interface{}
+ s any
name string
index []int
value int
{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)), ""},
}
}
-type FuncDDD func(...interface{}) error
+type FuncDDD func(...any) error
func (f FuncDDD) M() {}
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)
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
}
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")
}
f()
}
-func isNonNil(x interface{}) {
+func isNonNil(x any) {
if x == nil {
panic("nil interface")
}
var V = ValueOf
-func EmptyInterfaceV(x interface{}) Value {
+func EmptyInterfaceV(x any) Value {
return ValueOf(&x).Elem()
}
{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))},
{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) {
}
}
-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))
}
// 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
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++ {
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++ {
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{
{
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++ {
{
name: "StructI",
typ: PointerTo(TypeOf(StructI(want))),
- val: ValueOf(func() interface{} {
+ val: ValueOf(func() any {
v := StructI(want)
return &v
}()),
{
name: "StructIPtr",
typ: PointerTo(TypeOf(StructIPtr(want))),
- val: ValueOf(func() interface{} {
+ val: ValueOf(func() any {
v := StructIPtr(want)
return &v
}()),
// 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++ {
// 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++ {
// 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++ {
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)},
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 {
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()
}()
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,
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)
}
type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
type nameTest struct {
- v interface{}
+ v any
want string
}
{(*func() D1)(nil), ""},
{(*<-chan D1)(nil), ""},
{(*chan<- D1)(nil), ""},
- {(*interface{})(nil), ""},
+ {(*any)(nil), ""},
{(*interface {
F()
})(nil), ""},
type p3 p
type exportTest struct {
- v interface{}
+ v any
want bool
}
exportTests := []exportTest{
type S string
tests := []struct {
- in interface{}
+ in any
i, j int
- want interface{}
+ want any
}{
{
in: []int{1, 20, 300},
})
// Make sure assignment conversion works.
- var x interface{}
+ var x any
y := ValueOf(&x).Elem()
y.SetIterKey(i)
if _, ok := data[x.(string)]; !ok {
// 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
}
)
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())
// 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.
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))
}
{
// 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]
}
{
// 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]
}
{
// 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]
}
var implementsTests = []struct {
- x interface{}
- t interface{}
+ x any
+ t any
b bool
}{
{new(*bytes.Buffer), new(io.Reader), true},
}
var assignableTests = []struct {
- x interface{}
- t interface{}
+ x any
+ t any
b bool
}{
{new(chan int), new(<-chan int), true},
{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...) {
// 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()})
// 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)
}
// 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
}
// 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
// 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
}
// Make a func type.
- var ifunc interface{} = (func())(nil)
+ var ifunc any = (func())(nil)
prototype := *(**funcType)(unsafe.Pointer(&ifunc))
n := len(in) + len(out)
}
// 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
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
}
// 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
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{
}
// 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 {
}
// 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
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))
}
// 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})
}
// 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()
// 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{}
}
}
x := valueInterface(v, false)
if dst.NumMethod() == 0 {
- *(*interface{})(target) = x
+ *(*any)(target) = x
} else {
ifaceE2I(dst, x, target)
}
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)
}
//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
// 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
}
var dummy struct {
b bool
- x interface{}
+ x any
}
var fieldsTests = []struct {
testName string
- val interface{}
+ val any
expect []structField
}{{
testName: "SimpleStruct",
RS1
}
-type M map[string]interface{}
+type M map[string]any
type Rec1 struct {
*Rec2
tests := []struct {
name string
- fin interface{}
+ fin any
confirmValue int
}{
{"Pointer", regFinalizerPointer, -1},
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)
}
// 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) }.
//
// 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")
// 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")
v := 42
tests := []struct {
- v1 interface{}
- v2 interface{}
+ v1 any
+ v2 any
}{
{v1: v, v2: v},
{v1: &v, v2: &v},
}
siz := 0
- handles.Range(func(k, v interface{}) bool {
+ handles.Range(func(k, v any) bool {
siz++
return true
})
// 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
}
// 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
}
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:
}
}
-func panicValue(fn func()) (recovered interface{}) {
+func panicValue(fn func()) (recovered any) {
defer func() {
recovered = recover()
}()
}
var (
- setGCPercentBallast interface{}
- setGCPercentSink interface{}
+ setGCPercentBallast any
+ setGCPercentSink any
)
func TestSetGCPercent(t *testing.T) {
)
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
}
//go:nosplit
-func (l *dlogger) p(x interface{}) *dlogger {
+func (l *dlogger) p(x any) *dlogger {
if !dlogEnabled {
return l
}
}()
}
-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)
}
// 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")
}
}
-func printanycustomtype(i interface{}) {
+func printanycustomtype(i any) {
eface := efaceOf(&i)
typestring := eface._type.string()
//
// 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")
}
regArgs *abi.RegArgs
argp unsafe.Pointer
argSize uintptr
- panic interface{}
+ panic any
handleF func(info *siginfo, ctxt *sigctxt, gp2 *g) bool
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()
})
}
-func GCMask(x interface{}) (ret []byte) {
+func GCMask(x any) (ret []byte) {
systemstack(func() {
ret = getgcmask(x)
})
// For benchmarking.
-func BenchSetType(n int, x interface{}) {
+func BenchSetType(n int, x any) {
e := *efaceOf(&x)
t := e._type
var size uintptr
// 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<<h.B; x++ {
c.commit(triggerRatio)
}
-var escapeSink interface{}
+var escapeSink any
//go:noinline
-func escape(x interface{}) interface{} {
+func escape(x any) any {
escapeSink = x
escapeSink = nil
return x
}
}
-var hugeSink interface{}
+var hugeSink any
func TestHugeGCInfo(t *testing.T) {
// The test ensures that compiler can chew these huge types even on weakest machines.
benchSetType(b, make([]Node1024, 32))
}
-func benchSetType(b *testing.B, x interface{}) {
+func benchSetType(b *testing.B, x any) {
v := reflect.ValueOf(x)
t := v.Type()
switch t.Kind() {
close(done)
}
-func testTypeSwitch(x interface{}) error {
+func testTypeSwitch(x any) error {
switch y := x.(type) {
case nil:
// ok
return nil
}
-func testAssert(x interface{}) error {
+func testAssert(x any) error {
if y, ok := x.(error); ok {
return y
}
return nil
}
-func testAssertVar(x interface{}) error {
+func testAssertVar(x any) error {
var y, ok = x.(error)
if ok {
return y
var a bool
//go:noinline
-func testIfaceEqual(x interface{}) {
+func testIfaceEqual(x any) {
if x == "abc" {
a = true
}
runtime.KeepAlive(x)
}
{
- var x interface{}
+ var x any
verifyGCInfo(t, "stack eface", &x, infoEface)
runtime.KeepAlive(x)
}
verifyGCInfo(t, "heap PtrScalar", escape(new(PtrScalar)), trimDead(infoPtrScalar))
verifyGCInfo(t, "heap BigStruct", escape(new(BigStruct)), trimDead(infoBigStruct()))
verifyGCInfo(t, "heap string", escape(new(string)), trimDead(infoString))
- verifyGCInfo(t, "heap eface", escape(new(interface{})), trimDead(infoEface))
+ verifyGCInfo(t, "heap eface", escape(new(any)), trimDead(infoEface))
verifyGCInfo(t, "heap iface", escape(new(Iface)), trimDead(infoIface))
}
}
-func verifyGCInfo(t *testing.T, name string, p interface{}, mask0 []byte) {
+func verifyGCInfo(t *testing.T, name string, p any, mask0 []byte) {
mask := runtime.GCMask(p)
if !bytes.Equal(mask, mask0) {
t.Errorf("bad GC program for %v:\nwant %+v\ngot %+v", name, mask0, mask)
return mask
}
-var gcinfoSink interface{}
+var gcinfoSink any
-func escape(p interface{}) interface{} {
+func escape(p any) any {
gcinfoSink = p
return p
}
bssBigStruct BigStruct
bssString string
bssSlice []string
- bssEface interface{}
+ bssEface any
bssIface Iface
// DATA
- dataPtr = Ptr{new(byte)}
- dataScalarPtr = ScalarPtr{q: 1}
- dataPtrScalar = PtrScalar{w: 1}
- dataBigStruct = BigStruct{w: 1}
- dataString = "foo"
- dataSlice = []string{"foo"}
- dataEface interface{} = 42
- dataIface Iface = IfaceImpl(42)
+ dataPtr = Ptr{new(byte)}
+ dataScalarPtr = ScalarPtr{q: 1}
+ dataPtrScalar = PtrScalar{w: 1}
+ dataBigStruct = BigStruct{w: 1}
+ dataString = "foo"
+ dataSlice = []string{"foo"}
+ dataEface any = 42
+ dataIface Iface = IfaceImpl(42)
infoString = []byte{typePointer, typeScalar}
infoSlice = []byte{typePointer, typeScalar, typeScalar}
}
type EfaceKey struct {
- i interface{}
+ i any
}
func (k *EfaceKey) clear() {
)
var (
- uint16Eface interface{} = uint16InterfacePtr(0)
- uint32Eface interface{} = uint32InterfacePtr(0)
- uint64Eface interface{} = uint64InterfacePtr(0)
- stringEface interface{} = stringInterfacePtr("")
- sliceEface interface{} = sliceInterfacePtr(nil)
+ uint16Eface any = uint16InterfacePtr(0)
+ uint32Eface any = uint32InterfacePtr(0)
+ uint64Eface any = uint64InterfacePtr(0)
+ stringEface any = stringInterfacePtr("")
+ sliceEface any = sliceInterfacePtr(nil)
uint16Type *_type = efaceOf(&uint16Eface)._type
uint32Type *_type = efaceOf(&uint32Eface)._type
func (Tslice) Method1() {}
var (
- e interface{}
- e_ interface{}
+ e any
+ e_ any
i1 I1
i2 I2
ts TS
func BenchmarkAssertI2E(b *testing.B) {
i1 = tm
for i := 0; i < b.N; i++ {
- e = i1.(interface{})
+ e = i1.(any)
}
}
func BenchmarkAssertI2E2(b *testing.B) {
i1 = tm
for i := 0; i < b.N; i++ {
- e, ok = i1.(interface{})
+ e, ok = i1.(any)
}
}
func BenchmarkAssertI2E2Blank(b *testing.B) {
i1 = tm
for i := 0; i < b.N; i++ {
- _, ok = i1.(interface{})
+ _, ok = i1.(any)
}
}
func BenchmarkAssertE2E2(b *testing.B) {
e = tm
for i := 0; i < b.N; i++ {
- e_, ok = e.(interface{})
+ e_, ok = e.(any)
}
}
func BenchmarkAssertE2E2Blank(b *testing.B) {
e = tm
for i := 0; i < b.N; i++ {
- _, ok = e.(interface{})
+ _, ok = e.(any)
}
}
func TestNonEscapingConvT2E(t *testing.T) {
- m := make(map[interface{}]bool)
+ m := make(map[any]bool)
m[42] = true
if !m[42] {
t.Fatalf("42 is not present in the map")
"testing"
)
-var sink interface{}
+var sink any
func BenchmarkAtomicLoad64(b *testing.B) {
var x uint64
return (*MyNode)(unsafe.Pointer(node))
}
-var global interface{}
+var global any
func TestLFStack(t *testing.T) {
stack := new(uint64)
st := new(MemStats)
ReadMemStats(st)
- nz := func(x interface{}) error {
+ nz := func(x any) error {
if x != reflect.Zero(reflect.TypeOf(x)).Interface() {
return nil
}
return fmt.Errorf("zero value")
}
- le := func(thresh float64) func(interface{}) error {
- return func(x interface{}) error {
+ le := func(thresh float64) func(any) error {
+ return func(x any) error {
// These sanity tests aren't necessarily valid
// with high -test.count values, so only run
// them once.
return fmt.Errorf("insanely high value (overflow?); want <= %v", thresh)
}
}
- eq := func(x interface{}) func(interface{}) error {
- return func(y interface{}) error {
+ eq := func(x any) func(any) error {
+ return func(y any) error {
if x == y {
return nil
}
}
// Of the uint fields, HeapReleased, HeapIdle can be 0.
// PauseTotalNs can be 0 if timer resolution is poor.
- fields := map[string][]func(interface{}) error{
+ fields := map[string][]func(any) error{
"Alloc": {nz, le(1e10)}, "TotalAlloc": {nz, le(1e11)}, "Sys": {nz, le(1e10)},
"Lookups": {eq(uint64(0))}, "Mallocs": {nz, le(1e10)}, "Frees": {nz, le(1e10)},
"HeapAlloc": {nz, le(1e10)}, "HeapSys": {nz, le(1e10)}, "HeapIdle": {le(1e10)},
var BoolSink bool
func BenchmarkMapInterfaceString(b *testing.B) {
- m := map[interface{}]bool{}
+ m := map[any]bool{}
for i := 0; i < 100; i++ {
m[fmt.Sprintf("%d", i)] = true
}
- key := (interface{})("A")
+ key := (any)("A")
b.ResetTimer()
for i := 0; i < b.N; i++ {
BoolSink = m[key]
}
}
func BenchmarkMapInterfacePtr(b *testing.B) {
- m := map[interface{}]bool{}
+ m := map[any]bool{}
for i := 0; i < 100; i++ {
i := i
func TestDeferDeleteSlow(t *testing.T) {
ks := []complex128{0, 1, 2, 3}
- m := make(map[interface{}]int)
+ m := make(map[any]int)
for i, k := range ks {
m[k] = i
}
c64 complex64
c128 complex128
s string
- i0 interface{}
+ i0 any
i1 interface {
String() string
}
a [4]string
}
- m := map[interface{}]bool{}
+ m := map[any]bool{}
// Put a bunch of data in m, so that a bad hash is likely to
// lead to a bad bucket, which will lead to a missed lookup.
for i := 0; i < 1000; i++ {
// gcbits returns the GC type info for x, for testing.
// The result is the bitmap entries (0 or 1), one entry per byte.
//go:linkname reflect_gcbits reflect.gcbits
-func reflect_gcbits(x interface{}) []byte {
+func reflect_gcbits(x any) []byte {
ret := getgcmask(x)
typ := (*ptrtype)(unsafe.Pointer(efaceOf(&x)._type)).elem
nptr := typ.ptrdata / goarch.PtrSize
// Returns GC type info for the pointer stored in ep for testing.
// If ep points to the stack, only static live information will be returned
// (i.e. not for objects which are only dynamically live stack objects).
-func getgcmask(ep interface{}) (mask []byte) {
+func getgcmask(ep any) (mask []byte) {
e := *efaceOf(&ep)
p := e.data
t := e._type
framesz = f.nret
} else {
// Need to pass arguments on the stack too.
- framesz = unsafe.Sizeof((interface{})(nil)) + f.nret
+ framesz = unsafe.Sizeof((any)(nil)) + f.nret
}
if framecap < framesz {
// The frame does not contain pointers interesting for GC,
// A single goroutine runs all finalizers for a program, sequentially.
// If a finalizer must run for a long time, it should do so by starting
// a new goroutine.
-func SetFinalizer(obj interface{}, finalizer interface{}) {
+func SetFinalizer(obj any, finalizer any) {
if debug.sbrk != 0 {
// debug.sbrk never frees memory, so no finalizers run
// (and we don't have the data structures to record them).
// Note: KeepAlive should only be used to prevent finalizers from
// running prematurely. In particular, when used with unsafe.Pointer,
// the rules for valid uses of unsafe.Pointer still apply.
-func KeepAlive(x interface{}) {
+func KeepAlive(x any) {
// Introduce a use of x that the compiler can't eliminate.
// This makes sure x is alive on entry. We need x to be alive
// on entry for "defer runtime.KeepAlive(x)"; see issue 21402.
}
var finalizerTests = []struct {
- convert func(*int) interface{}
- finalizer interface{}
+ convert func(*int) any
+ finalizer any
}{
- {func(x *int) interface{} { return x }, func(v *int) { finalize(v) }},
- {func(x *int) interface{} { return Tintptr(x) }, func(v Tintptr) { finalize(v) }},
- {func(x *int) interface{} { return Tintptr(x) }, func(v *int) { finalize(v) }},
- {func(x *int) interface{} { return (*Tint)(x) }, func(v *Tint) { finalize((*int)(v)) }},
- {func(x *int) interface{} { return (*Tint)(x) }, func(v Tinter) { finalize((*int)(v.(*Tint))) }},
+ {func(x *int) any { return x }, func(v *int) { finalize(v) }},
+ {func(x *int) any { return Tintptr(x) }, func(v Tintptr) { finalize(v) }},
+ {func(x *int) any { return Tintptr(x) }, func(v *int) { finalize(v) }},
+ {func(x *int) any { return (*Tint)(x) }, func(v *Tint) { finalize((*int)(v)) }},
+ {func(x *int) any { return (*Tint)(x) }, func(v Tinter) { finalize((*int)(v.(*Tint))) }},
}
for i, tt := range finalizerTests {
go func() {
v := &bigValue{0xDEADBEEFDEADBEEF, true, "It matters not how strait the gate"}
old := *v
- runtime.SetFinalizer(v, func(v interface{}) {
+ runtime.SetFinalizer(v, func(v any) {
i, ok := v.(*bigValue)
if !ok {
t.Errorf("finalizer called with type %T, want *bigValue", v)
scavenge.parked = true
scavenge.timer = new(timer)
- scavenge.timer.f = func(_ interface{}, _ uintptr) {
+ scavenge.timer.f = func(_ any, _ uintptr) {
wakeScavenger()
}
fmt.Fprintf(out, "TEXT ·asyncPreempt(SB),NOSPLIT|NOFRAME,$0-0\n")
}
-func p(f string, args ...interface{}) {
+func p(f string, args ...any) {
fmted := fmt.Sprintf(f, args...)
fmt.Fprintf(out, "\t%s\n", strings.ReplaceAll(fmted, "\n", "\n\t"))
}
}
}
-func netpollDeadline(arg interface{}, seq uintptr) {
+func netpollDeadline(arg any, seq uintptr) {
netpolldeadlineimpl(arg.(*pollDesc), seq, true, true)
}
-func netpollReadDeadline(arg interface{}, seq uintptr) {
+func netpollReadDeadline(arg any, seq uintptr) {
netpolldeadlineimpl(arg.(*pollDesc), seq, true, false)
}
-func netpollWriteDeadline(arg interface{}, seq uintptr) {
+func netpollWriteDeadline(arg any, seq uintptr) {
netpolldeadlineimpl(arg.(*pollDesc), seq, false, true)
}
// a conversion requires an allocation because pointers to
// go:notinheap types (which pollDesc is) must be stored
// in interfaces indirectly. See issue 42076.
-func (pd *pollDesc) makeArg() (i interface{}) {
+func (pd *pollDesc) makeArg() (i any) {
x := (*eface)(unsafe.Pointer(&i))
x._type = pdType
x.data = unsafe.Pointer(&pd.self)
}
var (
- pdEface interface{} = (*pollDesc)(nil)
- pdType *_type = efaceOf(&pdEface)._type
+ pdEface any = (*pollDesc)(nil)
+ pdType *_type = efaceOf(&pdEface)._type
)
if powerRegisterSuspendResumeNotification == nil {
return // Running on Windows 7, where we don't need it anyway.
}
- var fn interface{} = func(context uintptr, changeType uint32, setting uintptr) uintptr {
+ var fn any = func(context uintptr, changeType uint32, setting uintptr) uintptr {
for mp := (*m)(atomic.Loadp(unsafe.Pointer(&allm))); mp != nil; mp = mp.alllink {
if mp.resumesema != 0 {
stdcall1(_SetEvent, mp.resumesema)
// We call these all the way here, late in init, so that malloc works
// for the callback functions these generate.
- var fn interface{} = ctrlHandler
+ var fn any = ctrlHandler
ctrlHandlerPC := compileCallback(*efaceOf(&fn), true)
stdcall2(_SetConsoleCtrlHandler, ctrlHandlerPC, 1)
}
// The implementation of the predeclared function panic.
-func gopanic(e interface{}) {
+func gopanic(e any) {
gp := getg()
if gp.m.curg != gp {
print("panic: ")
// TODO(rsc): Once we commit to CopyStackAlways,
// this doesn't need to be nosplit.
//go:nosplit
-func gorecover(argp uintptr) interface{} {
+func gorecover(argp uintptr) any {
// Must be in a function running as part of a deferred call during the panic.
// Must be called from the topmost function of the call
// (the function used in the defer statement).
import "unsafe"
//go:linkname plugin_lastmoduleinit plugin.lastmoduleinit
-func plugin_lastmoduleinit() (path string, syms map[string]interface{}, errstr string) {
+func plugin_lastmoduleinit() (path string, syms map[string]any, errstr string) {
var md *moduledata
for pmd := firstmoduledata.next; pmd != nil; pmd = pmd.next {
if pmd.bad {
// Because functions are handled specially in the plugin package,
// function symbol names are prefixed here with '.' to avoid
// a dependency on the reflect package.
- syms = make(map[string]interface{}, len(md.ptab))
+ syms = make(map[string]any, len(md.ptab))
for _, ptab := range md.ptab {
symName := resolveNameOff(unsafe.Pointer(md.types), ptab.name)
t := (*_type)(unsafe.Pointer(md.types)).typeOff(ptab.typ)
- var val interface{}
+ var val any
valp := (*[2]unsafe.Pointer)(unsafe.Pointer(&val))
(*valp)[0] = unsafe.Pointer(t)
"unsafe"
)
-var memSink interface{}
+var memSink any
func allocateTransient1M() {
for i := 0; i < 1024; i++ {
type Profile struct {
name string
mu sync.Mutex
- m map[interface{}][]uintptr
+ m map[any][]uintptr
count func() int
write func(io.Writer, int) error
}
}
p := &Profile{
name: name,
- m: map[interface{}][]uintptr{},
+ m: map[any][]uintptr{},
}
profiles.m[name] = p
return p
// Passing skip=0 begins the stack trace at the call to Add inside rpc.NewClient.
// Passing skip=1 begins the stack trace at the call to NewClient inside mypkg.Run.
//
-func (p *Profile) Add(value interface{}, skip int) {
+func (p *Profile) Add(value any, skip int) {
if p.name == "" {
panic("pprof: use of uninitialized Profile")
}
// Remove removes the execution stack associated with value from the profile.
// It is a no-op if the value is not in the profile.
-func (p *Profile) Remove(value interface{}) {
+func (p *Profile) Remove(value any) {
p.mu.Lock()
defer p.mu.Unlock()
delete(p.m, value)
// containsInlinedCall reports whether the function body for the function f is
// known to contain an inlined function call within the first maxBytes bytes.
-func containsInlinedCall(f interface{}, maxBytes int) bool {
+func containsInlinedCall(f any, maxBytes int) bool {
_, found := findInlinedCall(f, maxBytes)
return found
}
// findInlinedCall returns the PC of an inlined function call within
// the function body for the function f if any.
-func findInlinedCall(f interface{}, maxBytes int) (pc uint64, found bool) {
+func findInlinedCall(f any, maxBytes int) (pc uint64, found bool) {
fFunc := runtime.FuncForPC(uintptr(abi.FuncPCABIInternal(f)))
if fFunc == nil || fFunc.Entry() == 0 {
panic("failed to locate function entry")
// fmtJSON returns a pretty-printed JSON form for x.
// It works reasonbly well for printing protocol-buffer
// data structures like profile.Profile.
-func fmtJSON(x interface{}) string {
+func fmtJSON(x any) string {
js, _ := json.MarshalIndent(x, "", "\t")
return string(js)
}
func TestIssue8102(t *testing.T) {
// If this compiles with -race, the test passes.
type S struct {
- x interface{}
+ x any
i int
}
c := make(chan int)
close(c)
}()
var r MyT
- var i interface{} = r
+ var i any = r
issue12664_3 = i.(MyT)
<-c
}
func TestRaceCaseType(t *testing.T) {
var x, y int
- var i interface{} = x
+ var i any = x
c := make(chan int, 1)
go func() {
switch i.(type) {
func TestRaceCaseTypeBody(t *testing.T) {
var x, y int
- var i interface{} = &x
+ var i any = &x
c := make(chan int, 1)
go func() {
switch i := i.(type) {
// spurious extra instrumentation of the initial interface
// value.
var x, y int
- m := make(map[int]map[int]interface{})
- m[0] = make(map[int]interface{})
+ m := make(map[int]map[int]any)
+ m[0] = make(map[int]any)
c := make(chan int, 1)
go func() {
switch i := m[0][1].(type) {
}
func TestRaceEfaceWW(t *testing.T) {
- var a, b interface{}
+ var a, b any
ch := make(chan bool, 1)
go func() {
a = 1
c := make(chan bool)
v := 0
go func() {
- go func(x interface{}) {
+ go func(x any) {
}(v)
c <- true
}()
func TestRaceEmptyInterface1(t *testing.T) {
c := make(chan bool)
- var x interface{}
+ var x any
go func() {
x = nil
c <- true
func TestRaceEmptyInterface2(t *testing.T) {
c := make(chan bool)
- var x interface{}
+ var x any
go func() {
x = &Point{}
c <- true
func TestRaceTypeAssert(t *testing.T) {
c := make(chan bool, 1)
x := 0
- var i interface{} = x
+ var i any = x
go func() {
y := 0
i = y
// Repeat so that at least one iteration gets reuse.
for i := 0; i < 10; i++ {
c := make(chan int)
- p := &sync.Pool{New: func() interface{} { return make([]byte, 10) }}
+ p := &sync.Pool{New: func() any { return make([]byte, 10) }}
x := p.Get().([]byte)
x[0] = 1
p.Put(x)
func TestNoRacePool(t *testing.T) {
for i := 0; i < 10; i++ {
- p := &sync.Pool{New: func() interface{} { return make([]byte, 10) }}
+ p := &sync.Pool{New: func() any { return make([]byte, 10) }}
x := p.Get().([]byte)
x[0] = 1
p.Put(x)
data unsafe.Pointer
}
-func efaceOf(ep *interface{}) *eface {
+func efaceOf(ep *any) *eface {
return (*eface)(unsafe.Pointer(ep))
}
// adjustment takes care of them.
type _panic struct {
argp unsafe.Pointer // pointer to arguments of deferred call run during panic; cannot move - known to liblink
- arg interface{} // argument to panic
+ arg any // argument to panic
link *_panic // link to earlier panic
pc uintptr // where to return to in runtime if this panic is bypassed
sp unsafe.Pointer // where to return to in runtime if this panic is bypassed
}
}
-var efaceCmp1 interface{}
-var efaceCmp2 interface{}
+var efaceCmp1 any
+var efaceCmp2 any
func BenchmarkEfaceCmpDiff(b *testing.B) {
x := 5
const _64bit = unsafe.Sizeof(uintptr(0)) == 8
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
}{
{runtime.G{}, 236, 392}, // g, but exported for testing
{runtime.Sudog{}, 56, 88}, // sudog, but exported for testing
var nerr int
-func err(t *testing.T, format string, args ...interface{}) {
+func err(t *testing.T, format string, args ...any) {
t.Errorf(format, args...)
// cut errors off after a while.
var methodValueCallFrameObjs [1]stackObjectRecord // initialized in stackobjectinit
func stkobjinit() {
- var abiRegArgsEface interface{} = abi.RegArgs{}
+ var abiRegArgsEface any = abi.RegArgs{}
abiRegArgsType := efaceOf(&abiRegArgsEface)._type
if abiRegArgsType.kind&kindGCProg != 0 {
throw("abiRegArgsType needs GC Prog, update methodValueCallFrameObjs")
}
// Pass a value to escapeMe to force it to escape.
-var escapeMe = func(x interface{}) {}
+var escapeMe = func(x any) {}
// Test that when F -> G is inlined and F is excluded from stack
// traces, G still appears.
}
type cbFunc struct {
- goFunc interface{}
+ goFunc any
}
func (f cbFunc) cName(cdecl bool) string {
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 {
}
//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() {
// 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
// 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
// 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
// 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
// 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.
// 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
// 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
// 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
// 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
// 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
// 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
// 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
// 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
// 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
// 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
// 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
C.runCPUHogThread()
})
- time.Sleep(1*time.Second)
+ time.Sleep(1 * time.Second)
pprof.StopCPUProfile()
// 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
// 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
// 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
+//go:build windows && cgo
// +build windows,cgo
package main
// 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.
// 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)
}
// 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")
}
}
// 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.
//
// 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()
//
// 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())
// 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-- {
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) {
package strings
-func (r *Replacer) Replacer() interface{} {
+func (r *Replacer) Replacer() any {
r.once.Do(r.buildOnce)
return r.r
}
off int64
n int
want string
- wanterr interface{}
+ wanterr any
}{
{0, 10, "0123456789", nil},
{1, 10, "123456789", io.EOF},
)
// 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()
}()
//
// A Value must not be copied after first use.
type Value struct {
- v interface{}
+ v any
}
// ifaceWords is interface{} internal representation.
// 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) {
// 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")
}
//
// 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")
}
// 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")
}
// 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 {
}
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)},
}
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},
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"},
)
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:
// 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 {
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()
}
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()
}
//
// 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.
// 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 {
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 {
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
//
// 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 {
// 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 {
//
// 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
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 {
}
// 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
}
}
}
//
// 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
}
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
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 })
}
},
})
m.Load(i)
if i%mapSize == 0 {
- m.Range(func(k, _ interface{}) bool {
+ m.Range(func(k, _ any) bool {
m.Delete(k)
return false
})
// 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
}
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 {
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)
}
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
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
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()
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]
return
}
-func (m *DeepCopyMap) Delete(key interface{}) {
+func (m *DeepCopyMap) Delete(key any) {
m.mu.Lock()
dirty := m.dirty()
delete(dirty, key)
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
}
}
-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
}
// 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)
}
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))
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
})
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)
}
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)
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) {
// 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
})
// 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 {
// 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
}
//
// 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()
}
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
i := 0
p := Pool{
- New: func() interface{} {
+ New: func() any {
i++
return i
},
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
})
}
-var globalSink interface{}
+var globalSink any
func BenchmarkPoolSTW(b *testing.B) {
// Take control of GC.
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)
}
// 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
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.
// 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<<dequeueBits-1) == head {
if val == nil {
val = dequeueNil(nil)
}
- *(*interface{})(unsafe.Pointer(slot)) = val
+ *(*any)(unsafe.Pointer(slot)) = val
// Increment head. This passes ownership of slot to popTail
// and acts as a store barrier for writing the slot.
// popHead removes and returns the element at the head of the queue.
// It returns false if the queue is empty. It must only be called by a
// single producer.
-func (d *poolDequeue) popHead() (interface{}, bool) {
+func (d *poolDequeue) popHead() (any, bool) {
var slot *eface
for {
ptrs := atomic.LoadUint64(&d.headTail)
}
}
- val := *(*interface{})(unsafe.Pointer(slot))
+ val := *(*any)(unsafe.Pointer(slot))
if val == dequeueNil(nil) {
val = nil
}
// popTail removes and returns the element at the tail of the queue.
// It returns false if the queue is empty. It may be called by any
// number of consumers.
-func (d *poolDequeue) popTail() (interface{}, bool) {
+func (d *poolDequeue) popTail() (any, bool) {
var slot *eface
for {
ptrs := atomic.LoadUint64(&d.headTail)
}
// We now own slot.
- val := *(*interface{})(unsafe.Pointer(slot))
+ val := *(*any)(unsafe.Pointer(slot))
if val == dequeueNil(nil) {
val = nil
}
return (*poolChainElt)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(pp))))
}
-func (c *poolChain) pushHead(val interface{}) {
+func (c *poolChain) pushHead(val any) {
d := c.head
if d == nil {
// Initialize the chain.
d2.pushHead(val)
}
-func (c *poolChain) popHead() (interface{}, bool) {
+func (c *poolChain) popHead() (any, bool) {
d := c.head
for d != nil {
if val, ok := d.popHead(); ok {
return nil, false
}
-func (c *poolChain) popTail() (interface{}, bool) {
+func (c *poolChain) popTail() (any, bool) {
d := loadPoolChainElt(&c.tail)
if d == nil {
return nil, false
return ENOSYS
}
-func fsCall(name string, args ...interface{}) (js.Value, error) {
+func fsCall(name string, args ...any) (js.Value, error) {
type callResult struct {
val js.Value
err error
}
c := make(chan callResult, 1)
- f := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
+ f := js.FuncOf(func(this js.Value, args []js.Value) any {
var res callResult
if len(args) >= 1 { // on Node.js 8, fs.utimes calls the callback without any arguments
var (
funcsMu sync.Mutex
- funcs = make(map[uint32]func(Value, []Value) interface{})
+ funcs = make(map[uint32]func(Value, []Value) any)
nextFuncID uint32 = 1
)
// 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++
// | 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
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)
// 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})
}
// 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})
}
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 {
// 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)
// 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)
// 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)
}
}
-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})
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)
}
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
})
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
<-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()
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
}
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()
SYS_FCNTL = 500 // unsupported
)
-type Sockaddr interface {
-}
+type Sockaddr any
type SockaddrInet4 struct {
Port int
}
// 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.
// 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)
}
// 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)
}
import "testing"
-var global interface{}
+var global any
var allocsPerRunTests = []struct {
name 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
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)
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.
}
// 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')
}
Parent string
Path string
Data []byte
- Values []interface{}
+ Values []any
Generation int
IsSeed 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))
// 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")
}
// 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)
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)
}
// A CheckError is the result of Check finding an error.
type CheckError struct {
Count int
- In []interface{}
+ In []any
}
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 {
// t.Error(err)
// }
// }
-func Check(f interface{}, config *Config) error {
+func Check(f any, config *Config) error {
if config == nil {
config = &defaultConfig
}
// 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
}
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 {
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)
// 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()
// 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()
// 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()
// 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
// 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...))
}
// 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()
// 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()
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)
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.
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()
}
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...))
}
}
// 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)
// 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)
//
// 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 {
// 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))
}
// 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.
}
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
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
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"},
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)
}
return ""
}
-func typeOf(arg interface{}) string {
+func typeOf(arg any) string {
return fmt.Sprintf("%T", arg)
}
name string
input string
output string
- data interface{}
+ data any
ok bool
}
{".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},
return sum
}
-func echo(arg interface{}) interface{} {
+func echo(arg any) any {
return arg
}
return s.String()
}
-func mapOfThree() interface{} {
+func mapOfThree() any {
return map[string]int{"three": 3}
}
func TestEvalFieldErrors(t *testing.T) {
tests := []struct {
name, src string
- value interface{}
+ value any
want string
}{
{
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
},
// 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")
},
tests := []struct {
name string
input string
- data interface{}
+ data any
wantErr string
}{
{
// 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
// 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))
}
// 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))
}
// 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.
// 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
}
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
// 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
// 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,
}
// 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...))
}
// 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{"$"}
// 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
{"block definition", `{{block "foo"}}hello{{end}}`, hasError, ""},
}
-var builtins = map[string]interface{}{
+var builtins = map[string]any{
"printf": fmt.Sprintf,
"contains": strings.Contains,
}
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.
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
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,
}
// 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:
return t
}
-func goFunc(arg interface{}, seq uintptr) {
+func goFunc(arg any, seq uintptr) {
go arg.(func())()
}
}
}
-func die(format string, args ...interface{}) {
+func die(format string, args ...any) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
os.Exit(1)
}