目前在项目中主要有三种使用反射的场景 测试 reflect.DeepEqual 测试结果(一般为结构复杂的struct)和期望内容是否相同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 func TestSomeFunc (t *testing.T) { testCases := []struct { input map [string ]interface {} output map [string ]interface {} }{ { }, } for _, cc := range testCases { res := SomeFunc(cc.input) if !reflect.DeepEqual(res, cc.output) { t.Errorf("Expect: %v, get: %v\n" , cc.output, res) } } }
某个接口是否被实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package mainimport ( "fmt" "reflect" ) type Interface interface { XFunc() error } type InterfaceImpl struct {}func (f *InterfaceImpl) XFunc () error { return nil } func main () { ht := reflect.TypeOf((*Interface)(nil )).Elem() st := reflect.TypeOf(&InterfaceImpl{}) fmt.Println(st.Implements(ht)) }
获取struct的元数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 type StructField struct { FieldName string TagName string FieldValue interface {} } v := reflect.ValueOf(model).Elem() fields := []*StructField{} for i := 0 ; i < v.NumField(); i++ { fieldInfo := v.Type().Field(i) tag := fieldInfo.Tag tagName := tag.Get("db" ) valueField := v.Field(i) fields = append (fields, &StructField{ FieldName: fieldInfo.Name, TagName: tagName, FieldValue: valueField.Interface(), }) }