How to check if a map contains a specific key in Go?
Hello everyone! I just started learning Go, and I have a problem with checking if a key exists in a map. In Python, I'm used to just writing `if key in dict:`, but Go doesn't have such a construct.
Let's say I have a map of users:
```go
users := map[int]string{
1: "Alice",
2: "Bob",
3: "Charlie",
}
```
I need to check if a user with ID = 4 exists. I tried this code:
```go
if users[4] != "" {
fmt.Println("User found!")
}
```
But this doesn't work if the key's value is an empty string. For example, if I add `4: ""`, my code can't distinguish between a missing key and an empty value. The same goes for numeric maps: if the value is 0, the check will also break.
I know that in Go, accessing a non-existent key returns the zero value of the type. But
No answers yet.
Log in to leave an answer
Blogs
Functional Programming in Java: From Lambdas to Stream API