add an item to a slice of type int in go

To add an item to a slice of type int in Go, you can use the built-in append() function which returns a new slice containing the original slice with the added item. The append() function adds the new item to the end of the slice.

Here's an example of adding an item to a slice of type int:

main.go
package main

import "fmt"

func main() {
  slice := []int{1, 2, 3}  // original slice
  fmt.Println(slice)  // [1 2 3]

  // add item to slice
  slice = append(slice, 4)
  fmt.Println(slice)  // [1 2 3 4]

  // add item to slice using indexing
  slice = append(slice[:2], append([]int{5}, slice[2:]...)...)
  fmt.Println(slice)  // [1 2 5 3 4]
}
347 chars
17 lines

In the second example, we first append {5} to the start of a slice containing only the value {2}, and then append the result of that to slice[2:] using the 3 dot ... syntax to indicate that each item of the slice is being passed as a separate parameter. This results in the {5} integer being inserted between the {2} and {3} in the slice.

related categories

gistlibby LogSnag