首页 > 解决方案 > 在 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)
}

标签: gointerface

解决方案


该类型interface{}可以用作非常通用的类型,允许将任何其他类型分配给它。

因此,如果一个函数接收interface{}到 ,您可以将任何值传递给它。

这是因为在 Go 中,要满足接口的类型,它必须只实现接口声明的所有方法。

由于interface{}是一个空接口,任何类型都会满足它。

另一方面,要满足[]interface{}它的类型必须是空接口的实际切片。

因此,如果您需要一个可以接收任何值的通用函数,只需interface{}按照示例中所示使用即可。

请注意,这interface{}将允许您传递值或指针引用,因此您可以将指针或值模糊地传递给该函数。


推荐阅读