如何更改接口参数?

How to change param that is interface?

我用来处理 DB 的库为 save/load 数据提供了方便的接口,无需强制转换

Put(c context.Context, key *Key, src interface{}) (*Key, error)
Get(c context.Context, key *Key, dst interface{}) error

但是,我无法理解 GET 方法如何工作。我尝试用最简单的代码片段复制行为,但没有用。

import "fmt"

type MyType struct {
    inside string
}

func setVal(dst *MyType) {
    someVal := MyType{"new"}
    *dst = someVal
}

func setValGen(dst interface{}) {
    someVal := MyType{"new"}
    dst = someVal
}


func main() {
    typeDstA := MyType{"old"}
    setVal(&typeDstA)
    fmt.Println(typeDstA)     //changed to new

    typeDstB := MyType{"old"}
    setValGen(&typeDstB)
    fmt.Println(typeDstB)     //remains old
}

他们如何使 Get 函数接受 interface{} 并更改指针目标?

他们很可能在使用反射。

https://play.golang.org/p/kU5gKjG0P8

someVal := MyType{"new"}
v := reflect.ValueOf(dst).Elem()
if v.CanSet() {
    v.Set(reflect.ValueOf(someVal))
}