我正在尝试使用通用例程处理特定组件之间的消息。其中一部分涉及读取字节数组并使用 json.Marshal 和 json.Unmarshal 并调用回调。
我试图将接口传递给需要特定结构的函数,但我不知道目标结构的类型。在下面的代码中,函数 r() 如何调用函数 cb() 并传入正确的数据?
package main
import (
"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)
}
相关分类