英文:
Go interface using `var` keyword?
问题
我正在参考这个链接中的代码:Golang中的接口
在"类型断言"部分,主函数中的第一段代码有一行如下:var val interface {} = "Geeks for Geeks"
我不理解这个语法。通常,我们在包级别创建一个接口类型,如下所示:
type some_interface interface {
// 方法
}
然后创建一个该接口类型的变量 var s some_interface 来使用。这行代码实际上是做什么的?它是一个"匿名接口"(类似于匿名结构体)吗?使用这种方法声明接口有什么用?
提前感谢
英文:
I am referring to the code in this link: Interfaces in Golang
Under the "Type assertions" section, the first piece of code has a line like so in the main function: var val interface {} = "Geeks for Geeks"
I did not understand this syntax. Usually, we create an interface type at the package level like
type some_interface interface {
// methods
}
and then create a variable of this interface type var s some_interface for use. What does this line actually do? Is it an "anonymous interface" (like anonymous struct). What is the use of declaring an interface using this method?
Thanks in advance
答案1
得分: 2
这是一个空接口,基本上可以是任何类型。
空接口
指定零个方法的接口类型被称为空接口:
interface{}
空接口可以保存任何类型的值。(每种类型至少实现了零个方法。)
空接口被用于处理未知类型的值的代码。例如,fmt.Print 接受任意数量的 interface{} 类型的参数。
英文:
It is an empty interface, basically any type.
> The empty interface
>
> The interface type that specifies zero methods is known as the empty
> interface:
>
> interface{}
>
> An empty interface may hold values of any type. (Every type implements
> at least zero methods.)
>
> Empty interfaces are used by code that handles values of unknown type.
> For example, fmt.Print takes any number of arguments of type
> interface{}.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论