怎么给slice加一个Insert方法呢?而不用丑陋的两次append….

package main

import (
	"fmt"
	"reflect"
)

func Insert(slice interface{}, pos int, value interface{}) interface{} {

	v := reflect.ValueOf(slice)

	ne := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(value)), 1, 1)

	ne.Index(0).Set(reflect.ValueOf(value))
	v = reflect.AppendSlice(v.Slice(0, pos), reflect.AppendSlice(ne, v.Slice(pos, v.Len())))

	return v.Interface()
}
func main() {
	slice := []int{1, 2}

	fmt.Println(Insert(slice, 1, 99))

	slice2 := []string{"a", "c", "d"}

	slice2 = Insert(slice2, 0, "b").([]string)
	fmt.Println(Insert(slice2, 4, "e"))
}

  

posted on 2018-07-18 16:42  荣耀王者  阅读(659)  评论(0编辑  收藏  举报

导航