LoginSignup
8
7

More than 5 years have passed since last update.

slice か判定する

Last updated at Posted at 2016-01-10
foo.([]interface{})

だとうまくキャストできないので.

今のところ reflect を使う以外なさそうにみえる.

import reflect

func mergeStruct(curr, next interface{}) interface{} {
    cVal := reflect.ValueOf(curr)
    nVal := reflect.ValueOf(next)

    if cVal.Kind() == reflect.Slice && nVal.Kind() == reflect.Slice {
        return mergeSlice(cVal, nVal)
    }
}

interface{} を interface{} のまま使うなら, reflect.AppendSlice は使えない.

func mergeSlice(curr, next reflect.Value) []interface{} {
    res := make([]interface{}, curr.Len()+next.Len())

    for i := 0; i < curr.Len(); i++ {
        res[i] = curr.Index(i).Interface()
    }

    for i := 0; i < next.Len(); i++ {
        res[i+curr.Len()] = next.Index(i).Interface()
    }

    return res
}

参考

https://golang.org/pkg/reflect/
https://code.google.com/p/gorilla/source/browse/exp/schema/flattener.go?r=89399a125333592d8ad1105a3994ee956ee08c63

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7