remove an item from an array of type int in go

To remove an item from an array of type int in Go, we can make use of slicing. Here's an example:

main.go
arr := []int{1, 2, 3, 4, 5} // create an array of type int

// remove the item at index 2 (i.e. 3rd item)
arr = append(arr[:2], arr[3:]...)

fmt.Println(arr) // [1 2 4 5]
171 chars
7 lines

In the above code, we first create an array arr containing five integers. We then use the append function to slice the array and remove the item at index 2 (i.e. the 3rd item). The first parameter to append is the slice of arr from the start to the index before the item we want to remove, and the second parameter is the slice from the index after the item we want to remove to the end of the array.

Finally, we print the updated array which now contains [1 2 4 5] - the array with the third item removed.

related categories

gistlibby LogSnag