package lib
import "reflect"
// data := []string{"A", "B", "C", "D"}
// data = append([]string{"Prepend Item"}, data...)
// 实现类似javascript中array的unshift功能
func Unshift(slice, v interface{}) interface{} {
var typ = reflect.TypeOf(slice)
if typ.Kind() == reflect.Slice {
var vv = reflect.ValueOf(slice)
var tmp = reflect.MakeSlice(typ, vv.Len()+1, vv.Cap()+1)
tmp.Index(0).Set(reflect.ValueOf(v))
var dst = tmp.Slice(1, tmp.Len())
reflect.Copy(dst, vv)
return tmp.Interface()
}
panic("not a slice")
}
package lib
import (
"reflect"
"testing"
)
func TestUnshift(t *testing.T) {
var a = []int{1, 2, 3}
a = Unshift(a, 22).([]int)
if !reflect.DeepEqual(a, []int{22, 1, 2, 3}) {
t.Error("a:", a)
}
var b = []string{"a", "b"}
b = Unshift(b, "haha").([]string)
if !reflect.DeepEqual(b, []string{"haha", "a", "b"}) {
t.Error("b:", b)
}
}