【发布时间】:2013-06-27 11:36:17
【问题描述】:
我目前对 golangs reflect 包的行为感到绝望,对我来说这似乎根本不一致。
1) 据我了解,reflect.Value 似乎带有一个指向基础值的指针。 例如。如果我打电话
var s string
v1 := reflect.ValueOf(&s).Elem()
v2 := v1
v2.SetString("Hello World!")
fmt.Println(s)
它打印我“Hello World!”。 但是,这似乎不适用于通过调用 Field() 获得的 reflect.Value。
val := ... //Assign a reflect.Value to it
nextval := val.Field(0) //Make sure that Field exists and is of type map
nextval = reflect.MakeMap(reflect.MapOf(KEY, ELEM))
nextval.SetMapIndex(Some_value_of_type_KEY, Something_of_type_ELEM)
fmt.Println(nextval.MapKeys()
fmt.Println(val.Field(index).MapKeys())
打印出来
[Some_value_of_type_KEY]
[]
这是一个主要的烦恼。有人知道为什么会这样吗?
================================================ ====
2) 考虑函数
func Test(v interface{}) {
val := reflect.ValueOf(v)
if val.Kind() != reflect.Struct {
fmt.Println("It is a struct")
}
}
如果我用任何结构作为参数调用它,它会打印“这是一个结构”。 但是,我将无法使用 val 为 v 中的内容分配新值, 由于该值不可寻址。通过以下方式解决:
func Test(v interface{}) {
val := reflect.ValueOf(&v).Elem()
if val.Kind() != reflect.Struct {
fmt.Println("This never get's printed!")
}
}
根据文档,我假设通过使用 '&' 我使用指向 v 的指针并通过调用 Elem() 我得到它指向的元素,因此 val.Kind() 仍然应该返回同一件事情。它没有。 val.Kind() 现在是一个 reflect.Interface。
有没有办法不用去
valForTestingKind := reflect.ValueOf(v)
valForSettingNewValue := reflect.ValueOf(&v).Elem()
因为这感觉有点不对。
【问题讨论】:
标签: reflection go