remove an item from a slice of type int in go

To remove an item from a slice of type int in Go, one approach is to create a new slice without the item. Here's an example implementation:

main.go
func removeInt(slice []int, item int) []int {
    index := -1
    for i, val := range slice {
        if val == item {
            index = i
            break
        }
    }
    if index == -1 {
        return slice
    }
    return append(slice[:index], slice[index+1:]...)
}
278 chars
14 lines

The removeInt function takes in a slice of int and an item to remove. It first searches for the index of the item in the slice using a for loop. If the item is not found, the original slice is returned as is. Otherwise, a new slice is created by concatenating the elements before and after the index of the item to be removed.

Here's an example usage:

main.go
someSlice := []int{1, 2, 3, 4, 5}
itemToRemove := 3
someSlice = removeInt(someSlice, itemToRemove)
fmt.Println(someSlice) // Output: [1 2 4 5]
143 chars
5 lines

In this example, we remove the item with value 3 from the someSlice slice using the removeInt function.

related categories

gistlibby LogSnag