为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 interface{} 作为特定结构传递给函数?

如何将 interface{} 作为特定结构传递给函数?

Go
守着一只汪 2021-10-11 10:53:06
我正在尝试使用通用例程处理特定组件之间的消息。其中一部分涉及读取字节数组并使用 json.Marshal 和 json.Unmarshal 并调用回调。我试图将接口传递给需要特定结构的函数,但我不知道目标结构的类型。在下面的代码中,函数 r() 如何调用函数 cb() 并传入正确的数据?package mainimport (    "encoding/json"    "fmt"    "reflect")type Bottom struct {    Foo string}func cb(b *Bottom) {    fmt.Println("5. ", b)}func r(t interface{}, buf []byte) {    _ = json.Unmarshal(buf, &t)    fmt.Println("2. ", reflect.TypeOf(t))    fmt.Println("3. ", t)    cb(&t)}func main() {    x := Bottom{Foo: "blah"}    var y Bottom    buf, _ := json.Marshal(x)    fmt.Println("1. ", x)    r(&y, buf)}
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 181 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信