Go delete function: delete key-value pairs from the map

table of Contents

description

Syntax and parameters

Usage example

Precautions

Delete non-existent key

The deleted key is nil


 

description

The delete function is a built-in function of Go, which deletes elements from the map according to the specified key. If the key to be deleted is nil or there is no such element, delete does not operate.

 

Syntax and parameters

Function signature

func delete(m map[Type]Type1, key Type)
parameter name meaning
m Map to operate
key Key to be removed from m

Return value : The delete function does not have any return value.

 

Usage example

Use the delete function to delete the key-value pairs in the map:

package main

import "fmt"

func main() {
	demo := make(map[string]interface{})
	demo["code"] = "Golang"
	demo["author"] = "Robert Griesemer"
	delete(demo, "author")
	fmt.Println(demo)
	// outputs: map[code:Golang]
}

 

Precautions

Delete non-existent key

When deleting a key that does not exist, delete does not perform any operation.

package main

import "fmt"

func main() {
	demo := make(map[string]interface{})
	delete(demo, "author")
	fmt.Println(demo)
	// outputs: map[]
}

The deleted key is nil

When the deleted key is nil, delete does not operate.

package main

import "fmt"

func main() {
	demo := make(map[interface{}]interface{})
	demo["platform"] = "CentOS"
	delete(demo, nil)
	fmt.Println(demo)
	// outputs: map[platform:CentOS]
}

 

Guess you like

Origin blog.csdn.net/TCatTime/article/details/114188640