Câu hỏi phỏng vấn Golang
Câu hỏi

How to check if a Map contains a key in Go?

Câu trả lời

To check if a map contains a key in Go, you can use several methods, but the most common and recommended approach is the "comma-ok" idiom. This method is efficient and straightforward, allowing you to determine both the presence of a key and retrieve its corresponding value if it exists.

Using the Comma-Ok Idiom

The "comma-ok" idiom utilizes the feature in Go where accessing a map by key returns two values: the value associated with the key and a boolean that indicates whether the key exists in the map. Here's how you can implement this:

go Copy
package main

import "fmt"

func main() {
    myMap := map[string]int{"apple": 1, "banana": 2, "cherry": 3}

    // Check if the key "banana" exists in the map
    value, exists := myMap["banana"]
    if exists {
        fmt.Printf("Key 'banana' exists with value %d\n", value)
    } else {
        fmt.Println("Key 'banana' does not exist in the map")
    }
}

In this example, exists will be true if the key "banana" is found in myMap, and false otherwise. The variable value will hold the value associated with "banana" if it exists, or the zero value of the map's value type if it does not exist[1][2][3].

Alternative Methods

Using a Conditional Statement

If you are only interested in whether the key exists and do not need the value, you can use a conditional statement with the blank identifier _ to ignore the first return value:

go Copy
package main

import "fmt"

func main() {
    myMap := map[string]int{"apple": 1, "banana": 2, "cherry": 3}

    // Check if the key "cherry" exists in the map
    if _, ok := myMap["cherry"]; ok {
        fmt.Println("Key 'cherry' exists in the map")
    } else {
        fmt.Println("Key '...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Name some advantages of Goroutines over threads

middle

Why would you prefer to use an empty struct{} ?

senior

What is an idiomatic way of representing enums in Go?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào