'What is the "any" type in Go 1.18?

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 blackgreen