Menu
Coddy logo textTech

Add and Delete Elements

Lesson 19 of 21 in Coddy's Slices and Maps in Golang course.

Maps in Golang act just like arrays and slices. To add a new element to the map, we use the same syntax as an array, except that in the map, we specify both the key and the value. For example, suppose we have a map like this:

var books = map[string]int{
    "Python":     1,
    "JavaScript": 2,
    "Rust":       3,
}

To add a new element, we do it like this:

books["Golang"] = 4

And if we print the map, we should see our Golang there:

map[Golang:4 JavaScript:2 Python:1 Rust:3]

You may notice that maps don't order the elements. This is because maps don't care much about ordering things; they prioritize the performance of retrieving results quickly.

Note that when we add new elements to the map, we should use the same type as the map's value type. 

For example, we cannot do this:

books["Golang"] = "Learn Golang"

Because the value in the original map is an integer type, not a string type.

Now that we've learned how to add and get an element, what if we need to delete an element from the map?

For this, there is a built-in function called delete. The syntax is as follows:

Suppose we need to delete the first element, which is "Python":

delete(books, "Python")

We use the keyword delete, and between parentheses, we put the map name and the key that we want to delete. In our case, it's "Python".

challenge icon

Challenge

Easy

In the given code, we define a map with 6 elements. Perform the following steps:

  • Add a new element with the key 6 and value "orange".
  • Delete the element with the key 10.
  • Using a for loop, print the map in an ordered way starting from 1 to the end.

Try it yourself

package main

import 	"fmt"


func main() {
	// Define a map with 6 elements don't change This! 
	fruits := map[int]string{
		1: "apple",
		2: "banana",
		3: "cherry",
		4: "date",
		5: "elderberry",
		10: "fig",
	}

	// Add a new element with the key 6 and value "orange"
	 

	// Delete the element with the key 10
 

	// Using a for loop, print the map in an ordered way starting from 1 to the end

}

All lessons in Slices and Maps in Golang