Delete an Element
Lesson 14 of 21 in Coddy's Slices and Maps in Golang course.
Up until now, we've learned how to add elements to a slice, how to copy a slice, how to compare slices, and how to get the length of a slice.
Now, the question: How do we delete a specific element from a slice?
Unfortunately, there is no built-in function for this task, but if we combine what we've learned, we can achieve this operation.
Let's suppose we have a slice like this:
books := []string{"Golang", "JavaScript", "Java", "Python", "PostgreSQL", "TypeScript"}Can you think of what we can do if we need to obtain a new slice without a specific element, for example, removing "PostgreSQL"?
Here we can use slice operators, if you remember:
books := []string{"Golang", "JavaScript", "Java", "Python", "PostgreSQL", "TypeScript"}
fmt.Println(books[:4])
fmt.Println(books[5:])We will get two slices like this:
[Golang JavaScript Java Python]
[TypeScript]Here, we have successfully removed the element "PostgreSQL", but we need these slices to be combined into one. So, we can use the <strong>append</strong> function to concatenate the two slices:
books := []string{"Golang", "JavaScript", "Java", "Python", "PostgreSQL", "TypeScript"}
books = append(books[:4], books[5:]...)
fmt.Println(books)In this code, we use the <strong>append</strong> function to add the second slice (<strong>books[5:]</strong>) to the first part (<strong>books[:4]</strong>). Note that we use <strong>...</strong> to convert the second part into individual elements to add them to the first part.
The result will be:
[Golang JavaScript Java Python TypeScript]We have successfully removed the "PostgreSQL" item from the <strong>books</strong> slice.
Challenge
EasyWrite a program that takes input from the user and deletes the item from the slice where the number provided by the user represents the index of the item to delete.
Try it yourself
package main
import "fmt"
func main() {
// Get input from the user Don't Change This!
var x int
fmt.Scanln(&x)
// Define a slice Don't Change This!
lang := []string{"Rust", "Java", "JavaScript", "Golang", "Haskell", "C#"}
// Delete the item at the specified index
// Print the updated slice
}All lessons in Slices and Maps in Golang
1Introduction
Introduction3Slices Behind the Scene
Slice is an ArraySlice with MakeCopy a SliceDelete an ElementRecap Challenge #1Recap Challenge #2