gitee.com/zhongguo168a/gocodes@v0.0.0-20230609140523-e1828349603f/datax/mapx/copy.go (about)

     1  package mapx
     2  
     3  //
     4  func CopyNoCover(from, to map[string]interface{}) {
     5  	cloneMap(from, to, false)
     6  	return
     7  }
     8  
     9  //
    10  func Copy(from, to map[string]interface{}) {
    11  	cloneMap(from, to, true)
    12  	return
    13  }
    14  
    15  // isCover 如果目标已经存在值,是否覆盖
    16  func cloneMap(from, to map[string]interface{}, isCover bool) (r interface{}) {
    17  	for key, val := range from {
    18  		toVal, has := to[key]
    19  		if has && isCover == false {
    20  			_, ok := toVal.(map[string]interface{})
    21  			if !ok {
    22  				continue
    23  			}
    24  			if toVal == nil {
    25  				continue
    26  			}
    27  		}
    28  		to[key] = cloneAny(val, toVal, isCover)
    29  	}
    30  	return to
    31  }
    32  
    33  func cloneArray(from, to []interface{}, isCover bool) (r []interface{}) {
    34  	for i, val := range from {
    35  		to[i] = cloneAny(val, to[i], isCover)
    36  	}
    37  	return to
    38  }
    39  
    40  func cloneAny(fromVal, toVal interface{}, isCover bool) (r interface{}) {
    41  	switch fv := fromVal.(type) {
    42  	case map[string]interface{}:
    43  		var m map[string]interface{}
    44  		if fv == nil {
    45  			return m
    46  		}
    47  		if toVal == nil {
    48  			toVal = m
    49  		}
    50  		switch tv := toVal.(type) {
    51  		case map[string]interface{}:
    52  			if tv == nil {
    53  				tv = map[string]interface{}{}
    54  			}
    55  			r = cloneMap(fv, tv, isCover)
    56  		case IFromMap:
    57  			tv.FromMap(fv)
    58  		default:
    59  			panic("to val is not map[string]interface{}")
    60  		}
    61  	case []interface{}:
    62  		toVal = make([]interface{}, len(fv), cap(fv))
    63  		switch tv := toVal.(type) {
    64  		case []interface{}:
    65  			r = cloneArray(fv, tv, isCover)
    66  		default:
    67  			panic("to val is not []interface{}")
    68  		}
    69  	default:
    70  		//fmt.Printf("clone any: %T, %v\n", fv, fv)
    71  		r = fv
    72  	}
    73  	return
    74  }