如何在Go中合并任意数据结构?

时间:2016-11-18 14:39:47

标签: go data-structures

我有一种情况,我有两个数据结构。每个都是静态类型为interface{},可以是int,string,slice或map。该函数应该能够将这两个数据结构合并在一起,除了在某些情况下(例如,您不能将字符串与映射合并)。我写了下面的代码,但是我想知道是否有更优雅的方法。

package main

import (
    "fmt"
    "reflect"
)

func mergeDataStructures(a, b interface{}) (interface{}, error) {
    var retVal interface{}

    switch a.(type) {
    case string, int:
        switch b.(type) {
        case string, int:
            retVal = []interface{}{}
            retVal = append(retVal.([]interface{}), b)
            retVal = append(retVal.([]interface{}), a)
        case []interface{}:
            retVal = append(retVal.([]interface{}), a)
        case map[interface{}]interface{}:
            return nil, fmt.Errorf("unable to merge string with map")
        default:
            return nil, fmt.Errorf("unknown value type %q", reflect.TypeOf(b))
        }
    case []interface{}:
        switch b.(type) {
        case string, int:
            retVal = []interface{}{}
            retVal = append(retVal.([]interface{}), a.([]interface{})...)
            retVal = append(retVal.([]interface{}), b)
        case []interface{}:
            retVal = []interface{}{}
            retVal = append(retVal.([]interface{}), a.([]interface{})...)
            retVal = append(retVal.([]interface{}), b.([]interface{})...)
        case map[interface{}]interface{}:
            return nil, fmt.Errorf("unable to merge slice with map")
        default:
            return nil, fmt.Errorf("unknown value type %q", reflect.TypeOf(b))
        }
    case map[interface{}]interface{}:
        switch b.(type) {
        case string, int:
            return nil, fmt.Errorf("unable to merge map with string")
        case []interface{}:
            return nil, fmt.Errorf("unable to merge map with slice")
        case map[interface{}]interface{}:
            retVal = make(map[interface{}]interface{})
            for k, v := range a.(map[interface{}]interface{}) {
                retVal.(map[interface{}]interface{})[k] = v
            }
            for k, v := range b.(map[interface{}]interface{}) {
                retVal.(map[interface{}]interface{})[k] = v
            }
        default:
            return nil, fmt.Errorf("unknown value type %q", reflect.TypeOf(b))
        }
    default:
        return nil, fmt.Errorf("unknown value type %q", reflect.TypeOf(a))
    }

    return retVal, nil
}

func main() {
  var a, b interface{}

  a = []interface{}{1,2,3}
  b = 4
  c, err := mergeDataStructures(a, b)
  if err != nil {
    panic(err)
  }
  fmt.Printf("%#v\n", c) // prints: []interface{}{1,2,3,4}
}

0 个答案:

没有答案