OneBite.Dev - Coding blog in a bite size

remove a specific element from an array in Go

Code snippet on how to remove a specific element from an array in Go

  package main 
  import "fmt"
 
  func main() { 
   arr := []int{ 10, 20, 30, 40, 50 } 
   
   fmt.Println("Array:", arr)
   
   removeIndex := 2 
   arr = append(arr[:removeIndex], arr[removeIndex+1:]...)
  
   fmt.Println("Array after removing index 2:", arr) 
  } 

This code is written in Go language and it will remove a specific element from an array. First, we need to import the package “fmt” which is used to print out something in Go. Then create an array called “arr” with some numbers as its elements. We can use the Println function from the fmt package to print out the current array. Then we need to define the index number of the element we want to remove from our array. In the code, the index of the element we want to remove is 2. After that, we need to apply the append function to our array, this function will remove the element from the array and combine two parts of the array together. Finally, we can print out the new array after removing our element.

go