delete()
is an inbuilt function that deletes an element with a specified key from a map. Below is the prototype of delete()
in Go, which shows the key
and map m
:
func delete(m map[Type]Type1, key Type)
The delete()
function requires 2 parameters for input. The first one is map m
, which can have key of type Type
and element of type Type1
. Moreover, the key
defines which element of the map needs to be deleted.
Below is an example of how you can use the delete()
function:
package mainimport "fmt"func main() {student := make(map[string]int)student["Samia"] = 25student["Sana"] = 21student["Ali"] = 20fmt.Println(student)delete(student,"Samia")fmt.Println(student)}
As shown in the code above, we first create a map that contains data on students. The map stores the student’s name as the key and their age as the element. After adding elements to the map, we then delete an element with key Samia
from the map student
. After comparing the prints before and after using the delete function, we can observe that the element with key Samia
has been deleted.
Free Resources