golang的reflect

引用自 http://www.jb51.net/article/115002.htm

不同结构体字段赋值函数如下。

函数说明:传入参数from和to都是指针变量。只支持不同结构体同名且相同值类型字段赋值(可优化,加一个字段映射,并兼容int与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
}

  

猜你喜欢

转载自www.cnblogs.com/gauze/p/8984581.html