3

In Visual Studio Code, the auto-complete tool (which I presume is gopls?) gives the following template:

m.Range(func(key, value any) bool {
    
})

where m is a sync.Map. the type any is not recognized, but is put there.

What is any? Can I put the type I want and hope Go 1.18 to do implicit type conversion for me? For example:

m.Range(func(k, v string) { ... })

which will give k, v as string inside the callback, without having to do type cast myself?

TylerH
  • 20,799
  • 66
  • 75
  • 101
xrfang
  • 1,754
  • 4
  • 18
  • 36
  • Related question (possible duplicate: https://stackoverflow.com/questions/71628061/difference-between-any-interface-as-constraint-vs-type-of-argument) – TylerH May 18 '22 at 14:19

1 Answers1

6

any is a new predeclared identifier and a type alias of interface{}.

It comes from issue 49884, CL 368254 and commit 2580d0e.

The issue mentions about interface{}/any:

It's not a special design, but a logical consequence of Go's type declaration syntax.

You can use anonymous interfaces with more than zero methods:

func f(a interface{Foo(); Bar()}) {
   a.Foo()
   a.Bar()
}

Analogous to how you can use anonymous structs anywhere a type is expected:

func f(a struct{Foo int; Bar string}) {
   fmt.Println(a.Foo)
   fmt.Println(a.Bar)
}

An empty interface just happens to match all types because all types have at least zero methods.
Removing interface{} would mean removing all interface functionality from the language if you want to stay consistent / don't want to introduce a special case.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250