go - 在 Golang 中传递 interface{} 或 []interface{}
问题描述
有了这个片段,为什么它允许 interface{} 传递给函数而不是 []interface。有什么区别?我知道错误的含义(已将其注释到函数中),但我不确定错误的含义。
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{}
可以用作非常通用的类型,允许将任何其他类型分配给它。
因此,如果一个函数接收interface{}
到 ,您可以将任何值传递给它。
这是因为在 Go 中,要满足接口的类型,它必须只实现接口声明的所有方法。
由于interface{}
是一个空接口,任何类型都会满足它。
另一方面,要满足[]interface{}
它的类型必须是空接口的实际切片。
因此,如果您需要一个可以接收任何值的通用函数,只需interface{}
按照示例中所示使用即可。
请注意,这interface{}
将允许您传递值或指针引用,因此您可以将指针或值模糊地传递给该函数。
推荐阅读
- groovy - SoapUI:使用属性传输传输 groovy 脚本结果
- php - 异常:Illuminate \ Broadcasting \ BroadcastException PusherBroadcaster.php:119 中没有消息
- gesture - Hololens 模拟手势
- c# - 删除换行符
- javascript - 一本书的几位作者在 SQL
- javascript - 状态更改后组件未重新渲染
- sql - 获取所有具有运行总数的唯一组合
- mysql - 统计相似属性值
- facebook - 通过 facebook api 为页面创建评论
- javascript - 理解带有未捕获承诺的消息