ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
使用场景: 类似Java的BeanUtil.copyPropertity等工具类 ~~~ type Animal struct { Name string Age int Weight float64 } type Person struct { Name string Age int } type FieldMap map[string]bool func isStructPointer(obj interface{}) bool { if reflect.TypeOf(obj).Kind() != reflect.Ptr { return false } return reflect.TypeOf(obj).Kind() == reflect.Struct || reflect.TypeOf(obj).Elem().Kind() == reflect.Struct } func getAllFieldName(param interface{}) FieldMap { result := make(FieldMap) t := reflect.TypeOf(param).Elem() fieldNum := t.NumField() for i := 0; i < fieldNum; i++ { field := t.Field(i) fieldName := field.Name result[fieldName] = true } return result } func CopyObjects(source interface{}, dest interface{}) error { if !isStructPointer(source) || !isStructPointer(dest) { return errors.New("object must be struct pointer") } sourceFieldMap := getAllFieldName(source) t := reflect.TypeOf(dest).Elem() fieldNum := t.NumField() for i := 0; i < fieldNum; i++ { field := t.Field(i) if _, ok := sourceFieldMap[field.Name]; ok { // 取出source中该字段的值 value := reflect.ValueOf(source).Elem().FieldByName(field.Name) reflect.ValueOf(dest).Elem().FieldByName(field.Name).Set(value) } } return nil } func TestCopyObjects(t *testing.T) { person := new(Person) animal := &Animal{ Name: "Bear", Age: 15, Weight: 200, } t.Log(CopyObjects(animal, person)) t.Log("persion:", person) o1 := 10 o2 := 20 t.Log(CopyObjects(o1, o2)) } ~~~