func TestExtendStruct2(t *testing.T) { var t1 SimpleType t2 := strMap v1 := reflect.ValueOf(&t1).Elem() var src kiss.GetFunc = func(name string) (interface{}, bool) { x, ok := t2[name] return x, ok } kiss.ExtdStruct(v1, src) for i := 0; i < v1.Type().NumField(); i++ { f := v1.Type().Field(i) except, ok := t2[f.Name] actual := fmt.Sprint(v1.FieldByName(f.Name).Interface()) if !ok || except != actual { t.Errorf("extend field %s fail, except %s, actual %s", f.Name, except, actual) } } }
func extend() { fmt.Println("extend struct") var u1 User var u2 User u2.Name = "tom" u2.Age = 11 u2.Single = true v1 := reflect.ValueOf(&u1).Elem() v2 := reflect.ValueOf(&u2).Elem() var src kiss.GetFunc = func(name string) (interface{}, bool) { return v2.FieldByName(name).Interface(), true } kiss.ExtdStruct(v1, src) fmt.Println("u1", u1) }
func TestExtendStruct3(t *testing.T) { var t1 SimpleType var t2 SimpleType t2.A_bool = true t2.A_byte = byte(127) t2.A_float32 = 3.2 t2.A_float64 = 6.4 t2.A_int = -1 t2.A_int16 = -16 t2.A_int32 = -32 t2.A_int64 = -64 t2.A_int8 = -8 t2.A_string = "string" t2.A_uint16 = 16 t2.A_uint32 = 32 t2.A_uint64 = 64 t2.A_uint8 = 8 t2.A_unit = 1 v1 := reflect.ValueOf(&t1).Elem() v2 := reflect.ValueOf(&t2).Elem() var src kiss.GetFunc = func(name string) (interface{}, bool) { return v2.FieldByName(name).Interface(), true } kiss.ExtdStruct(v1, src) for i := 0; i < v1.Type().NumField(); i++ { f := v1.Type().Field(i) except := v2.FieldByName(f.Name).Interface() actual := v1.FieldByName(f.Name).Interface() if except != actual { t.Errorf("extend field %s fail, except %s, actual %s", f.Name, except, actual) } } }