Golang Slices

Just some notes for working with slices in Go. Mostly JavaScript array equivalent functions.

// unshift: add to index 0
func unshift(slice []interface{}, val interface{}) []interface{} {  
    return append([]interface{}{val}, slice...)
}
// shift: remove from index 0
func shift(slice []interface{}) []interface{} {  
    return slice[1:]
}
// push: add to end
func push(slice []interface{}, val interface{}) []interface{} {  
    return append(slice, val)
}
// pop: remove from end
func pop(slice []interface{}) (x interface{}, a []interface{}) {  
    x = slice[len(slice)-1]
    a = slice[:len(slice)-1]
    return
}
// delete: remove at index
func delete(slice []interface{}, i int) (a []interface{}) {  
    a = append(slice[:i], slice[i+1:]...)
    return
}
// insert: insert at index
func insert(slice []interface{}, i int, val interface{}) (a []interface{}) {  
    a = append(slice[:i], append([]interface{}{val}, slice[i+1:]...)...)
    return
}
comments powered by Disqus