Checking for Key Existence
Part of the Fundamentals section of Coddy's GO journey — lesson 89 of 109.
In Go, you can check if a key exists in a map using the two-value assignment form. This is important because accessing a non-existent key returns the zero value, which might be misleading.
Create a map of country codes:
countries := map[string]string{
"US": "United States",
"CA": "Canada",
}
// Check if "UK" exists in the map
value, exists := countries["UK"]
fmt.Println("Value:", value, "Exists:", exists)Result:
Value: Exists: falseThe exists boolean tells you whether the key was found. Use this in conditionals:
if _, exists := countries["US"]; exists {
fmt.Println("US is in the map")
}Result:
US is in the mapChallenge
BeginnerIn this challenge, you'll practice checking if a key exists in a map. You have a map of student grades, and you need to check if a specific student's grade exists in the map.
Complete the code to check if the student 'Emma' exists in the grades map, and print an appropriate message.
Try it yourself
package main
import "fmt"
func main() {
// Map of student grades
grades := map[string]int{
"John": 85,
"Sarah": 92,
"Mike": 78,
"Lisa": 95,
}
// Student to check
studentToCheck := "Emma"
// TODO: Check if studentToCheck exists in the grades map
// and store the result in a variable called 'exists'
// Hint: Use the comma-ok idiom
// Print the result
if exists {
fmt.Printf("%s's grade exists in the map\n", studentToCheck)
} else {
fmt.Printf("%s's grade does not exist in the map\n", studentToCheck)
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions9Pointers
What is a Pointer?Declaring Pointer VariablesThe Address-Of OperatorDereferencing PointersUsing Pointers in FunctionsNil PointersRecap - Understanding Pointers12Composite Types: Maps
Introduction to MapsDeclaring Map LiteralsCreating Maps with `make`Adding and Updating Key-ValueAccessing Map ValuesChecking for Key ExistenceDeleting Map EntriesMap LengthIterating Over MapsRecap - Key-Value Storage