Go – append/prepend item into slice

In Go, you can use append to insert the item into slice.

func append

func append(slice []Type, elems ...Type) []Type

append(sliceA, sliceB) function will append sliceB to sliceA and return a new slice, which means you can decide prepend/append by changing these two parameters.

Append

package main
import "fmt"
func main () {
  data := []string{"A", "B", "C", "D"}
  data = append(data, "Append Item")
  fmt.Println(data)
  // [A B C D Append Item]
}

Prepend

package main
import "fmt"
func main () {
  data := []string{"A", "B", "C", "D"}
  data = append([]string{"Prepend Item"}, data...)
  fmt.Println(data)
  // [Prepend Item A B C D]
}

Related Articles

Advertisements

8 thoughts on “Go – append/prepend item into slice

  1. Pingback: Go – append/prepend item into slice | Coding Air | The Winding Journal

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s