golang 反射获取 tag参考

golang反射 获取tag 2

golang参考3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package reflectutil

import (
	"fmt"
	"reflect"
)

func GetByTagNameFirst(tagName string, q interface{}) (string, error) {
	if q == nil {
		return "", fmt.Errorf("没有对象信息")
	}
	var kind = reflect.ValueOf(q).Kind()
	if kind != reflect.Ptr && kind != reflect.Struct {
		return "", fmt.Errorf("无法获取 tag")
	}
	//默认是结构体
	var val = reflect.TypeOf(q)
	if kind == reflect.Ptr {
		// 获取 指针类型
		val = val.Elem()
	}

	n := val.NumField()
	for i := 0; i < n; i++ {
		f := val.Field(i)
		tag, ok := f.Tag.Lookup(tagName)
		//f.Tag.get
		if ok {
			return tag, nil
		}
	}

	return "", nil
}


//拷贝数组
func CopySlice(dest interface{}, src interface{}) error {
	var destPtr = reflect.ValueOf(dest)
	if destPtr.Kind() != reflect.Ptr {
		//panic("不是数组地址")
		return fmt.Errorf("不是数组类型指针, dest %v",destPtr.Kind())
	}
	//var t2 = reflect.TypeOf(src).Kind()
	var source = reflect.ValueOf(src)
	if source.Kind() == reflect.Ptr {
		source = source.Elem()
	}
	if source.Kind() != reflect.Slice  && source.Kind() != reflect.Array {
		return fmt.Errorf("source 不是数组 %v",source.Kind())
	}

	var arr = destPtr.Elem()
	//var arr = make()
	for i:=0; i<source.Len();i++ {
			arr = reflect.Append(arr,source.Index(i).Elem())
	}
	//arr = reflect.Append(arr,source.Slice(0,source.Len()) )

	destPtr.Elem().Set(arr)
	return nil

}