【小記】go如何判斷key是否在map中


go如何判斷key是否在map中

判斷key是否存在, 判斷方式為value,ok := map[key], ok為true則存在

if _, ok := map[key], ok {
	//此為存在
}

if _, ok := map[key], !ok {
	//此為不存在
}

查詢方式如下,推薦使用check02的方式,因為check02在if里先運行表達式進行判斷,更為簡便

package main

import "fmt"

var(
	dict = map[string]int{"key1":1, "key2":2}
)

func check01(key string) {
	value, ok := dict[key]
	if ok {
		fmt.Println(value)
	}else {
		fmt.Println(key + " is not exist!")
	}
}


//簡化寫法
func check02(key string) {
	if value, ok := dict[key]; ok {
		fmt.Println(value)
	}else {
		fmt.Println(key + " is not exist!")
	}
}

func main() {
	check01("key1")
	check02("key3")
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM