← 返回列表

Go 语言 - 关键字 delete

Go 语言 delete 关键字用于删除哈希表 map 中的元素, 参数为 map 和其对应的 key 语法 Go 语言 delete 关键字语法格式如下 delete(map,key) 范例 /** * file: main.go * author: 简单教程(www.twle.cn) * Copyright © 2015-2065 www.twle.cn. 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

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

语法

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

delete(map,key)

范例

/**
 * file: main.go
 * author: 简单教程(www.twle.cn)
 * Copyright © 2015-2065 www.twle.cn. 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

打开资源 ↗

交流与评论