什么是“任何”输入GO 1.18?

发布于 2025-01-23 07:59:35 字数 409 浏览 3 评论 0原文

在Visual Studio代码中,自动完成工具(我认为是gopls?)给出以下模板:

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

哪里msync.map。 类型尚未识别,而是放在那里。

什么是任何?我可以将自己想要的类型放在我想要的1.18上做隐式对我的类型转换吗?例如:

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

哪个将给出kv作为回调内的字符串,而无需键入cast自己?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神爱温柔 2025-01-30 07:59:35

任何是新的 predeclared标识符类型的类型别名接口{}

它来自问题49884 cl 368254 提交2580D0E

问题提到了接口{}/任何

这不是特殊设计,而是GO类型声明语法的逻辑结果。

您可以使用具有超过零方法的匿名接口:

  func f(接口{foo(); bar()})
   A.foo()
   a.bar()
}
 

类似于如何在预期的任何地方使用匿名结构:


fmt.println(a.foo)
fmt.println(a.bar)
}

一个空的接口恰好匹配所有类型,因为所有类型至少具有零方法。
删除接口{}如果要保持一致/不想引入特殊情况,则将删除语言中的所有接口功能。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文