Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Add an element to slice in Go

Append function can be used in Go to add element to a slice. Append does not mutate / modify the existing collection, instead it adds the new element and returns a new slice. So reassigning the slice is required to see the added values in slice.

package main

import "fmt"

func main() {
    carSlice := []string{"Audi", "BMW"}

    fmt.Printf("BEFORE APPEND : %v \n", carSlice)

    carSlice = append(carSlice, "Benz")

    fmt.Printf("AFTER APPEND : %v", carSlice)

}


Output
BEFORE APPEND : [Audi BMW]
AFTER APPEND : [Audi BMW Benz]