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

时间:2019-03-06 11:51:11

标签: go

给出:

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

尝试一些配置,我遇到了与“期望*可找到,发现*客户”有关的编译错误,或者GetSaved函数实际上并没有改变我想要成为“输出变量”的地方。这可行吗,我只是没有正确地混合接口/指针/等?还是出于某些原因这不可能吗?

编辑:说明问题的working example

2 个答案:

答案 0 :(得分:1)

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

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

这是正在运行的link

答案 1 :(得分:0)

这有效,我将其转换为字节,然后将其解组回您的结构。希望这可以帮助。 :)     包主

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

运行链接:https://play.golang.org/p/NrBRcRmXRVZ