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)
}
The type interface{}
can be used as a very generic type that would allow any other type to be assigned to it.
So if a function receives interface{}
, you can pass any value to it.
That is because in Go, for a type to satisfy an interface it must just implement all methods the interface declares.
Since interface{}
is an empty interface, any type will satisfy it.
On the other hand, for a type to satisfy []interface{}
it must be an actual slice of empty interfaces.
So if you need a generic function that can receive any value, just use interface{}
as you show in your example.
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.