gpt4 book ai didi

Go:通过接口(interface){}指针传递返回值

转载 作者:IT王子 更新时间:2023-10-29 01:27:00 28 4
gpt4 key购买 nike

我有一个看起来像这样的函数:

func Foo(result interface{}) error {
...
json.Unmarshal([]byte(some_string), result)
...
}

这样调用:

var bar Bar
Foo(&bar)

通常,Foo 获取一个字符串,然后将其解码到结果中。但是,现在我需要更新它,以便 Foo 有时从另一个源加载数据并返回它。

type Loader func() (interface{})

func Foo(result interface{}, Loader load) error {
...
data := load()
// result = data ???
...
}

我有什么办法可以将这个新值分配给结果吗?我发现我可以将数据编码为一个字符串,然后将其解码为有效的结果,但我无法想象这是最好的方法。

最佳答案

你可以做到,

p := result.(*Bar)
*p = data

第一行是type assertion .

第二个将data 分配给解除引用的指针。为取消引用的指针赋值会更改引用地址处的值。

由于您不知道 resultdata 的底层类型,您能做的最好的事情就是使用类型断言开关。

switch v := data.(type) {
case Bar:
// If 'data' is of type 'Bar'
p, ok := result.(*Bar)
if(!ok){
// This means inputs were bad.
// 'result' and 'data' should both have the same underlying type.
fmt.Println("underlying types mismatch")
break;
}

*p = v

case Baz:
// If 'data' is of type 'Baz'
// Equivalent of above for 'Baz'
}

参见 switch statement 中的类型开关

关于Go:通过接口(interface){}指针传递返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36446675/

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