在Golang中传递接口{}或[]接口{} [英] Passing interface{} or []interface{} in Golang
问题描述
使用此代码段,为什么它允许接口{}传递到函数而不是[]接口。有什么区别?我知道错误说的是什么(已将其评论到函数中),但我不确定错误的含义。
With this snippet, why does it allow interface{} to pass into the function but not []interface. And what's the difference? I know what the error says (have commented it into the function), but I'm not sure what the error means.
https://play.golang.org/p/689R_5dswFX
package main
type smsSendRequest struct {
Recipients string `json:"recipients"`
}
// func action(pass interface{}) {
// //works
// }
func action(pass []interface{}) {
//cannot use data (type *smsSendRequest) as type []interface {} in argument to action
}
func main() {
to := "15551234567"
var data = &smsSendRequest{
Recipients: to,
}
action(data)
}
推荐答案
类型 interface {}
可用作非常通用的类型将允许任何其他类型分配给它。
The type interface{}
can be used as a very generic type that would allow any other type to be assigned to it.
所以如果函数接收ives interface {}
,你可以传递任何值。
So if a function receives interface{}
, you can pass any value to it.
这是因为在Go中,对于一个类型为了满足接口,它必须实现接口声明的所有方法。
That is because in Go, for a type to satisfy an interface it must just implement all methods the interface declares.
由于 interface {}
是一个空接口,任何类型都会满足它。
Since interface{}
is an empty interface, any type will satisfy it.
另一方面,对于满足 [] interface {}
的类型它必须是空接口的实际片段。
On the other hand, for a type to satisfy []interface{}
it must be an actual slice of empty interfaces.
因此,如果您需要一个可以接收任何值的泛型函数,只需使用 interface {}
正如您在示例中所示。
So if you need a generic function that can receive any value, just use interface{}
as you show in your example.
请注意 interface {}
将允许您传递值或指针引用,因此您可以将指针或值隐约传递给该函数。
Note that interface{}
will allow you to pass in either value or pointer references, so you can pass in pointers or values indistinctly to that function.
这篇关于在Golang中传递接口{}或[]接口{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!