Go Map containsKey()

1 개요[ | ]

Go Map containsKey()
package main

import "fmt"

func main() {
	dict := map[string]int{
		"apple":  40,
		"banana": 70,
	}

	var ok bool

	_, ok = dict["apple"]
	fmt.Println(ok) // true

	_, ok = dict["lemon"]
	fmt.Println(ok) // false
}
package main

import "fmt"

func main() {
	dict := map[string]int{
		"apple":  40,
		"banana": 70,
	}

	if _, ok := dict["apple"]; ok {
		fmt.Println("apple exists.") // apple exists.
	} else {
		fmt.Println("apple not exists.")
	}
	
	if _, ok := dict["lemon"]; ok {
		fmt.Println("lemon exists.")
	} else {
		fmt.Println("lemon not exists.") // lemon not exists.
	}
}
package main

import "fmt"

func main() {
	dict := map[string]int{
		"apple":  40,
		"banana": 70,
	}

	if val, ok := dict["apple"]; ok {
		fmt.Println("apple:", val) // apple: 40
	} else {
		fmt.Println("apple not exists.")
	}
	
	if val, ok := dict["lemon"]; ok {
		fmt.Println("lemon:", val)
	} else {
		fmt.Println("lemon not exists.") // lemon not exists.
	}
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}