跳至主要內容

二十二、Go 语言 – 关键字 delete

安图新小于 1 分钟Golang

Go语言 delete 关键字用于删除哈希表 map 中的元素, 参数为 map 和其对应的 key

语法

Go语言 delete 关键字语法格式如下

delete(map,key)

范例

/**
 * file: main.go
 * author: hotmindshare.com 安仔的技术指南
 * Copyright © 2015-2065 www.hotmindshare.com. All rights reserved.
 */
package main
import "fmt"
func main() {   
   /* 创建 map */
   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
   fmt.Println("原始 map")   
   /* 打印 map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   /* 删除元素 */
   delete(countryCapitalMap,"France");
   fmt.Println("Entry for France is deleted")  
   fmt.Println("删除元素后 map")   
   /* 打印 map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }

编译运行以上范例,输出结果如下:

$ go run main.go 
原始 map
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Entry for France is deleted
删除元素后 map
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi

上次编辑于:
贡献者: Andy