Go 方法如何获取接口类型的输出参数?

Go 方法如何获取接口类型的输出参数?,go,Go,鉴于: 尝试一些配置,我要么得到与“Expects*Savable,found*Customer”相关的编译错误,要么GetSaved函数实际上没有更改我想要的“输出变量”。这是否可行,而我只是没有得到正确的接口/指针/等组合?或者这是不可能的原因 编辑:说明问题的A。您可以使用反射来设置传递的接口。 即使结构引用作为接口传递,底层类型信息也不会丢失,我们可以使用反射 type Savable interface {} type Customer struct {} // satisfies '

鉴于:

尝试一些配置,我要么得到与“Expects*Savable,found*Customer”相关的编译错误,要么
GetSaved
函数实际上没有更改我想要的“输出变量”。这是否可行,而我只是没有得到正确的接口/指针/等组合?或者这是不可能的原因


编辑:说明问题的A。

您可以使用反射来设置传递的接口。 即使结构引用作为接口传递,底层类型信息也不会丢失,我们可以使用反射

type Savable interface {}
type Customer struct {} // satisfies 'Savable'

func GetSaved(id string, s Savable) {
  // somehow get a reference to the object from cache
  s = cachedObject 
  // alternately, something like:
  // json.Unmarshal(jsonFromDisk, &s)
}

func Foo() {
  c := Customer{}
  GetSaved("bob", &c)
}

这是正在运行的

我将其转换为字节,并将其解组回您的结构中。希望这有帮助。:) 包干管

package main

import (
    "fmt"
    "reflect"
)

type Savable interface {}

type Customer struct {
    Name string
} 

func GetSaved(id string, s Savable) {
    cached := Customer{ Name: id }
    c1 := reflect.ValueOf(cached)
    reflect.ValueOf(s).Elem().Set(c1)
}

func main() {
  c := Customer{}
  fmt.Printf("Before: %v\n", c)
  GetSaved("bob", &c)
  fmt.Printf("After: %v\n", c)
}

运行链接:

以上示例非常适合我在Go操场上使用。你打算做什么?这是个合理的主意。在Go中不可能执行类似于void foo(Customer*pCust){*pCust=cachedValue;}(C等价)的操作吗?
import (
    "encoding/json"
    "fmt"
)

type Savable interface{}
type Customer struct {
    Name string
} // satisfies 'Savable'

func GetSaved(id string, s Savable) {
    // somehow get a reference to the object from cache
    cached := Customer{Name: "Bob"}
    byt, _ := json.Marshal(cached)

    _ = json.Unmarshal(byt, &s)

}

func main() {
    c := Customer{}
    GetSaved("bob", &c)
    fmt.Println(c)
}