remove an element from the end of an array in go

To remove an element from the end of an array in Go, we can convert the array to a slice and then use slicing to remove the last element. Here's an example:

main.go
package main

import "fmt"

func main() {
  // create an array with some elements
  a := [4]string{"foo", "bar", "baz", "qux"}

  // convert the array to a slice
  s := a[:]

  // remove the last element from the slice
  s = s[:len(s)-1]

  fmt.Println(s) // prints [foo bar baz]
}
282 chars
17 lines

In this example, we create an array a with four elements. We then convert a to a slice s by using the slice operator [:], which creates a slice that includes all the elements of the array.

To remove the last element from the slice, we use slicing again. The expression s[:len(s)-1] creates a new slice that includes all the elements of s except for the last one.

Finally, we print the resulting slice s, which contains the original array's elements minus the last element.

related categories

gistlibby LogSnag