Golang delete() Function with Examples

Golang | delete() Function: Here, we are going to learn about the built-in delete() function with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 14, 2021 [Last updated : March 15, 2023]

delete() Function

In the Go programming language, delete() is a built-in function that is used to delete the element with the specified key from the map. If the map is nil or an empty map, delete is a no-op.

It accepts two parameters (m map[Type]Type1, key Type) and returns nothing.

Syntax

func delete(m map[Type]Type1, key Type)

Parameter(s)

  • map : The source map from which we have to remove the element.
  • key : The specified key.

Return Value

The return type of the delete() function is none.

Example 1

// Golang program to demonstrate the
// example of delete() function

package main

import (
	"fmt"
)

func main() {
	// Creating a map
	CountryCode := make(map[string]int)

	// Assigning keys and elements
	CountryCode["ind"] = 101
	CountryCode["aus"] = 102
	CountryCode["eng"] = 103
	CountryCode["pak"] = 104
	CountryCode["usa"] = 105

	// Deleting the element by key
	delete(CountryCode, "pak")

	//Printing the elements
	fmt.Println("India    :", CountryCode["ind"])
	fmt.Println("Australia:", CountryCode["aus"])
	fmt.Println("England  :", CountryCode["eng"])
	fmt.Println("Pakistan :", CountryCode["pak"])
	fmt.Println("USA      :", CountryCode["usa"])
}

Output

India    : 101
Australia: 102
England  : 103
Pakistan : 0
USA      : 105

Example 2

// Golang program to demonstrate the
// example of delete() function

package main

import (
	"fmt"
)

func main() {
	people := map[string]int{"Alex": 21, "Alvin": 37}
	fmt.Println("Before removing...")
	fmt.Println(people)

	// Deleting the element
	delete(people, "Alvin")

	fmt.Println("After removing...")
	fmt.Println(people)
}

Output

Before removing...
map[Alex:21 Alvin:37]
After removing...
map[Alex:21]

Golang builtin Package »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.