Removing elements from the middle of a slice

This is an example Go program illustrating removing an element from the middle of a slice.

package main

import (
        "fmt"
)

func main() {
        strings := []string{"one", "two", "three", "four"}
        for i := range strings {
                // Copy strings into c so that strings doesn't get altered by
                // append.
                c := make([]string, len(strings))
                copy(c, strings)
                // [0:i] includes elements from c[0] up to c[i-1]. If i=0, it
                // is empty.  c[i+1:] includes the elements from c[i+1] to
                // c[len(c)-1]. If i+1=len(c)-1, it is empty.  The final "..."
                // is necessary for appending a slice to a slice.
                sub := append(c[0:i], c[i+1:]...)
                for j := range sub {
                        fmt.Printf("%s ", sub[j])
                }
                fmt.Printf("\n")
        }
}

(download)

The output of the example looks like this:

two three four 
one three four 
one two four 
one two three 


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer