gpt4 book ai didi

go - 在 Golang 中传递 interface{} 或 []interface{}

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:42 27 4
gpt4 key购买 nike

对于这个片段,为什么它允许 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),任何类型都可以满足它。

另一方面,对于满足 []interface{} 的类型,它必须是空接口(interface)的实际 slice 。

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

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

关于go - 在 Golang 中传递 interface{} 或 []interface{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275913/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com