指针,数组和切片的结构值 [英] Struct value of pointer, array and slice
问题描述
我想有一个通用的方法,无论它是作为指针,切片还是数组提供,都将始终返回结构值.
I want to have a generic way which will always return the struct value no matter if it is provided as pointer, slice or array.
我的处理方法是:
func main() {
p := Person{}
if value(p).Kind() != reflect.Struct {
fmt.Printf("Error 1")
}
if value(&p).Kind() != reflect.Struct {
fmt.Printf("Error 2")
}
if value([]Person{p}).Kind() != reflect.Struct {
fmt.Printf("Error 3")
}
if value(&[]Person{p}).Kind() != reflect.Struct {
fmt.Printf("Error 4")
}
}
func value(m interface{}) reflect.Value {
v := reflect.ValueOf(m)
switch v.Kind() {
case reflect.Ptr:
v = v.Elem()
fallthrough
case reflect.Slice, reflect.Array:
v = v.Elem()
}
return v
}
如您所见,问题在于将结构从 slice
或 array
移出.
As you can see the problem lays with in getting the struct out of a slice
or array
.
如何扩展上述函数以从数组或切片中获取struct值?
更新:我要做的是将 [] People
变成 People
.
Update: What I want to do is turn []People
into People
.
推荐答案
If you just want the type even if the slice is nil, you can use something like this:
func value(m interface{}) reflect.Type {
t := reflect.Indirect(reflect.ValueOf(m)).Type()
if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
t = t.Elem()
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
return t
}
关于 Type.Elem()
,来自 http://golang.org/pkg/reflect/#Type :
//Elem返回类型的元素类型.
// Elem returns a type's element type.
//如果类型的种类不是Array,Chan,Map,Ptr或Slice,它会惊慌.
// It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.
//编辑对功能进行了更新,使其也适用于切片指针.
//edit updated the function to work on a slice of pointers as well.
这篇关于指针,数组和切片的结构值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!