在Go 1.18中,”any”类型是什么?

huangapple go评论80阅读模式
英文:

What is the "any" type in Go 1.18?

问题

在Visual Studio Code中,自动完成工具(我猜是gopls?)提供了以下模板:

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

其中m是一个sync.Map。类型any没有被识别,但是被放在了那里。

any是什么?我可以放入我想要的类型,并希望Go 1.18能够为我进行隐式类型转换吗?例如:

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

这将在回调函数中将kv作为字符串,而无需自己进行类型转换。

英文:

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?

答案1

得分: 6

any 是一个新的预声明标识符,也是 interface{} 的类型别名。

它来自于 issue 49884CL 368254commit 2580d0e

这个问题提到了 interface{}/any

> 这不是一个特殊的设计,而是 Go 语言类型声明语法的逻辑结果。
>
> 你可以使用带有多个方法的匿名接口:
>
> go > func f(a interface{Foo(); Bar()}) { > a.Foo() > a.Bar() > } >
>
> 类似于你可以在任何需要类型的地方使用匿名结构体:
>
> go > func f(a struct{Foo int; Bar string}) { > fmt.Println(a.Foo) > fmt.Println(a.Bar) > } >
>
> 空接口之所以能匹配所有类型,是因为所有类型至少有零个方法。
如果移除 interface{},那就意味着要从语言中移除所有接口功能,如果你想保持一致性/不想引入特殊情况的话。

英文:

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:
>
>go
>func f(a interface{Foo(); Bar()}) {
> a.Foo()
> a.Bar()
>}
>

>
>Analogous to how you can use anonymous structs anywhere a type is expected:
>
>go
>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.

huangapple
  • 本文由 发表于 2022年4月22日 14:34:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/71964357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定