Deleting an Element from a Go Slice

This blog post will present two techniques for deleting an element from an existing Go slice.

package main

import (
    "fmt"
)

func main() {
    i := 5

    aSlice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
    fmt.Println(aSlice)

    // Delete element at index i
    if i > len(aSlice)-1 {
        fmt.Println("Cannot delete element", i)
        return
    }

    aSlice = append(aSlice[:i], aSlice[i+1:]...)
    fmt.Println(aSlice)

    // Delete element at index i
    if i > len(aSlice)-1 {
        fmt.Println("Cannot delete element", i)
        return
    }

    // Replace element at index i with last element
    aSlice[i] = aSlice[len(aSlice)-1]
    // Remove last element
    aSlice = aSlice[:len(aSlice)-1]
    fmt.Println(aSlice)
}
$ go run deleteSlice.go
[0 1 2 3 4 5 6 7 8]
[0 1 2 3 4 6 7 8]
[0 1 2 3 4 8 7]