golang's reflect

Quoted from http://www.jb51.net/article/115002.htm

 

The assignment functions of different structure fields are as follows.

Function description: The incoming parameters from and to are both pointer variables. Only supports the assignment of fields with the same name and the same value type in different structures (optimized, adding a field map, and compatible with mutual assignment of int and string).

func CopyStruct (from, to interface{}) (bool) {

	typFrom := reflect.TypeOf(from)
	valFrom := reflect.Indirect(reflect.ValueOf(from))

	typTo := reflect.TypeOf(to)
	valTo := reflect.Indirect(reflect.ValueOf(to))

	if typFrom.Kind() != reflect.Ptr || typTo.Kind() != reflect.Ptr ||
	valFrom.Kind() != reflect.Struct || valTo.Kind() != reflect.Struct {
		return false
	}

	typTo = typTo.Elem ()
	typFrom = typFrom.Elem ()
	for i := 0; i < typTo.NumField(); i ++ {
		toField := typTo.Field(i)
		toFieldName := toField.Name
		_, exists := typFrom.FieldByName(toFieldName)
		if !exists || !valTo.FieldByName(toFieldName).CanSet() {
			continue
		}

		if valFrom.FieldByName(toFieldName).Kind() == valTo.FieldByName(toFieldName).Kind() {
			valTo.FieldByName(toFieldName).Set(valFrom.FieldByName(toFieldName))
		}
	}
	return true
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325300812&siteId=291194637