我用来与DB一起使用的库提供了方便的界面来保存/加载数据而无需强制转换
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))
}