Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go:通过接口{}指针传递返回值_Go_Interface - Fatal编程技术网

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

Go:通过接口{}指针传递返回值,go,interface,Go,Interface,我有一个函数如下所示: func Foo(result interface{}) error { ... json.Unmarshal([]byte(some_string), result) ... } var bar Bar Foo(&bar) 这就是所谓的: func Foo(result interface{}) error { ... json.Unmarshal([]byte(some_string), result)

我有一个函数如下所示:

func Foo(result interface{}) error {
     ...
     json.Unmarshal([]byte(some_string), result)
     ...
}
var bar Bar
Foo(&bar)
这就是所谓的:

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
第一行是a

第二个指针将
数据
分配给取消引用的指针。将值指定给取消引用的指针会更改引用地址处的值

由于您不知道
结果
数据
的基本类型,因此最好使用类型断言开关

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'
}

请参见

中的类型开关,Foo的第一个版本不起作用。解组到结果,而不是指向结果的指针
json.Unmarshal([]字节(一些字符串),result)
。唯一的问题是我不知道Foo中result的具体类型。这就是我使用接口{}的原因。我需要用reflect来解决这个问题吗?比尔,对不起,我忽略了它。用我能想到的最佳解决方案更新了答案。我希望您已经仔细考虑过使用此API。也许你可以把它改为只返回数据,而不是把它分配给指针?我需要为反序列化的情况传入一个引用的结构,不管我如何重构,我总是会最终到达加载结构或反序列化字符串的地步。它最终是类似于foo(结果接口{},加载程序)(接口{},错误)的东西,这很好,但不像我希望的那样干净。