Skip to content

Instantly share code, notes, and snippets.

@night-codes
Created November 3, 2015 06:06
Show Gist options
  • Save night-codes/c5a912de1e56689cf7de to your computer and use it in GitHub Desktop.
Save night-codes/c5a912de1e56689cf7de to your computer and use it in GitHub Desktop.
Golang slice insert func generator
package main
import (
"fmt"
"reflect"
)
func makeInsert(fptr interface{}) {
fn := reflect.ValueOf(fptr).Elem()
fn.Set(reflect.MakeFunc(fn.Type(), func(in []reflect.Value) []reflect.Value {
a, v := in[0].Elem(), reflect.Append(reflect.MakeSlice(reflect.SliceOf(in[2].Type()), 0, 0), in[2])
in[0].Elem().Set(reflect.AppendSlice(a.Slice(0, int(in[1].Int())), reflect.AppendSlice(v, a.Slice(int(in[1].Int()), a.Len()))))
return []reflect.Value{in[0]}
}))
}
func main() {
var ins func(*[]string, int, string) *[]string
makeInsert(&ins)
a := []string{`1a`, `2bb`, `3ccc`, `4dddd`}
ins(&a, 0, `test111`)
ins(&a, 3, `test222`)
fmt.Println(a)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment