gpt4 book ai didi

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

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

我正在尝试让一个通用例程处理特定组件之间的消息。其中一部分涉及读取字节数组并使用 json.Marshal 和 json.Unmarshal 以及调用回调。

我正在尝试将接口(interface)传递给需要特定结构的函数,但我不知道目标结构的类型。在下面的代码中,函数 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)
}

最佳答案

您需要 use a type assertion将您的接口(interface){}转换为您的函数所需的类型。然后,您可以添加错误检查以适当处理无法将参数转换为所需类型的情况。

请参阅演示解决方案的通用 Playground :http://play.golang.org/p/NYeoAVTEeA

在你的情况下,这意味着

cb(&t.(Bottom))

您可以添加错误检查:

bottom, ok := t.(Bottom)
if !ok {
// do something
}
cb(&bottom)

关于go - 如何将 interface{} 作为特定结构传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30605811/

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