dongpo0409 2018-05-10 15:00
浏览 1598
已采纳

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

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)
}
  • 写回答

1条回答 默认 最新

  • doulaozhi6835 2018-05-10 15:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动