What is the "any" type in Go 1.18?
Asked Answered
M

1

8

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?

Maryjanemaryjo answered 22/4, 2022 at 6:34 Comment(1)
Related question (possible duplicate: #71628561)Diacaustic
E
15

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.

Empoverish answered 22/4, 2022 at 6:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.