英文:
How a string could be of type interface{}
问题
我目前正在学习 go
,之前学过 C++
。每次遇到 interface
的时候我都会卡住。
例如:
s := []interface{}{"a", "b", "c"}
字符串如何成为一个接口?
我不明白 go
中的接口是以什么样的方式引入的。关于接口还有很多疑问。
如果能回答上述问题,并提供一些关于接口的学习资源,那就太好了。
提前感谢
英文:
I am currently learning go
after C++
. I just get stuck every time while facing interface
.
e.g:
s := []interface{}{"a", "b", "c"}
How string could be an interface?
I am not getting in what sense interface is introduced in go
. There are many more doubts regarding interface.
Answer to the above question and especially providing some learning resources regarding interface would be great.
Thanks in advance
答案1
得分: 4
根据定义,接口被定义为一组方法签名。因此,它用于指示另一种类型应该实现哪些方法。如果接口在接口声明体中没有指定任何方法签名,那么任何有效的类型都可以是该接口的类型,因为没有成为该接口的先决条件。
在你的例子中,切片包含了interface{}
类型,意味着任何类型都可以作为切片的有效输入候选。
s := []interface{}{"a", 1, false}
https://tour.golang.org/methods/9 是一个探索和学习Go语言的好地方。
英文:
By definition, an interface is defined as a set of method signatures. So it is used to indicate which methods should be implemented by another type. If the interface doesn't specify any method signatures in the interface declaration body then any valid type can be of the type of that interface since there are no prerequisites of being that interface.
In your example, the slice contains a type of interface{}
meaning any type can be a valid candidate as the slice input.
s := []interface{}{"a", 1, false}
https://tour.golang.org/methods/9 is a good place for exploring and learning go
.
答案2
得分: 0
你可以将接口看作一个容器,它包含一个值和该值的类型。
当你定义自己的接口时,编译器会确保你分配的值(存储在接口中)具有与你在接口定义中指定的方法相匹配的方法。
空接口 interface{}
没有方法,因此可以存储任何值,因为没有对任何特定方法的存在有任何期望。
如果你还没有看过,《Go 语言之旅》中的接口部分可以帮助你更好地理解。1
英文:
You can think of an interface as a container that holds a value and the type of that value.
When you define your own interfaces the compiler will ensure that the values you assign (store in the interface) have methods that match what you specified in your interface definition.
Empty interfaces, interface{}
, have no methods and can therefore store any value since there are no expectations for the existence of any particular methods.
If you have not already, check the section on interfaces in A Tour of Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论