【问题标题】:How to change param that is interface?如何更改接口参数?
【发布时间】:2017-11-30 00:18:45
【问题描述】:

我用来处理 DB 的库提供了方便的界面来保存/加载数据而无需强制转换

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

但是,我无法理解 GET 方法是如何工作的。我尝试用最简单的 sn-p 复制行为,但没有成功。

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{} 并更改指针目标?

【问题讨论】:

标签: pointers go contravariance


【解决方案1】:

他们很可能正在使用反射。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多