Learn How to remove an element from a slice in Golang
In this article, you are going to learn about how to remove an element from a slice in Go language.
In Go language, slice stores a similar type of element which is a sequence of variable length. You will get an error if you try to store different types of elements in the same slice. It is as similar as an array but the main difference is the size of a slice can be resized on the other hand an array size is fixed.
You can perform an action like removing an element from a slice easily. Let’s imagine you have stored students’ names in a slice and you want to remove an element from this. To do so, see the following code example:
package main
import "fmt"
func main() {
var studentName = []string{"Deven", "Alex", "John", "Smith", "Patel"}
fmt.Println(studentName)
studentName = RemoveIndex(studentName, 4)
fmt.Println(studentName)
}
func RemoveIndex(s []string, index int) []string {
return append(s[:index], s[index+1:]...)
}
// Output:
// [Deven Alex John Smith Patel]
// [Deven Alex John Smith]
Here, you can see that before removing an element there was a name “patel” exists and we remove it from the slice by mentioning the index number of a slice which is 4. Now if you want to remove “John” from the slice, all you need to do is to mention the index number of “John” which is 2 and you will be able to remove John from the slice.
Let’s see another example of removing an integer element from the slice. For example, you have a slice that contains students’ roll numbers and you want to remove a particular roll number from that slice. Follow the code example for this solution:
import "fmt"
func remove(slice []int, s int) []int {
return append(slice[:s], slice[s+1:]...)
}
func main() {
var studentRoll = []int{10, 22, 39, 41, 41}
fmt.Printf("Student Roll: %v\\n", studentRoll)
newStudentRoll := remove(studentRoll, 4)
fmt.Printf("New Stuedent ROll: %v\\n", newStudentRoll)
}
// Output:
// Student Roll: [10 22 39 41 41]
// New Stuedent ROll: [10 22 39 41]
Here, you can see that the duplicate value of the slice has been removed by mentioning the index number of that duplicate value.
You can also create a sub-slice instead of removing an element from the slice. Which will also give the same result but in a sub-slice. Let’s see an example of creating sub-slice also.
package main
import "fmt"
func main() {
var studentRoll = []int{10, 22, 39, 41, 41}
fmt.Printf("Student Roll: %v\\n", studentRoll)
newStudentRoll := studentRoll[:4]
fmt.Printf("New Student Roll: %v\\n", newStudentRoll)
}
// Output:
// Student Roll: [10 22 39 41 41]
// New Stuedent ROll: [10 22 39 41]
Here, newStudentRoll is a sub-slice formed from studentRoll slice and it contains the first four elements from the studentRoll slice.