Testing for Nil Maps
Part of the Logic & Flow section of Coddy's GO journey — lesson 28 of 68.
In Go, a map can have a special state called nil. A nil map is essentially an uninitialized map that points to nothing in memory. Understanding this concept is crucial because attempting to add keys to a nil map will cause your program to panic and crash.
Here's how a nil map occurs and what it looks like:
var myMap map[string]int
// myMap is nil at this pointWhen you declare a map variable without initializing it, Go automatically sets it to nil. While you can safely read from a nil map (it will return the zero value), trying to write to it will cause a panic:
// This is safe - returns 0
value := myMap["key"]
// This will panic!
myMap["key"] = 42To avoid this problem, you should always check if a map is nil before attempting to add keys to it. The check is straightforward:
if myMap == nil {
myMap = make(map[string]int)
}
myMap["key"] = 42 // Now this is safeThis simple check ensures your program won't crash when working with potentially uninitialized maps, making your code more robust and reliable.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a safe map initialization system that prevents panic errors by checking for nil maps before attempting to write operations. This challenge demonstrates the critical importance of validating map state before performing operations that could crash your program.
You will receive two inputs:
- A string representing the number of operations (e.g.,
"5") - A string containing operations in the format:
"operation1:key1:value1,operation2:key2:value2"where operations are either"check","init", or"add"(e.g.,"check:scores,init:scores,add:Alice:95,add:Bob:87,check:grades")
Your task is to:
- Create two map variables of type
map[string]intnamedscoresandgradeswithout initializing them (they will be nil) - Process each operation from the input string sequentially:
- For
"check"operations:- Check if the specified map is nil
- Print
"Map [map_name] is nil"if the map is nil - Print
"Map [map_name] is initialized"if the map is not nil
- For
"init"operations:- Initialize the specified map using
make(map[string]int) - Print
"Initialized map [map_name]"
- Initialize the specified map using
- For
"add"operations:- First check if the map is nil
- If the map is nil, print
"Cannot add to nil map [map_name]" - If the map is not nil, add the key-value pair and print
"Added [key]:[value] to [map_name]"
- Parse the operations by splitting the input string:
- Split by commas to get individual operations
- For each operation, split by colons to get the operation type and parameters
- Convert the value string to an integer for add operations
- After processing all operations, display the final state of both maps:
- For each map, if it's nil:
"Final state - [map_name]: nil" - For each map, if it's initialized:
"Final state - [map_name]: [count] entries"where count is the number of key-value pairs
- For each map, if it's nil:
Use the strconv package to convert value strings to integers for add operations. This challenge demonstrates how checking for nil maps before write operations prevents runtime panics and makes your code robust and reliable.
Cheat sheet
A nil map is an uninitialized map that points to nothing in memory. Attempting to add keys to a nil map will cause your program to panic and crash.
Declaring a map without initializing it creates a nil map:
var myMap map[string]int
// myMap is nil at this pointReading from a nil map is safe (returns zero value), but writing to it will panic:
// This is safe - returns 0
value := myMap["key"]
// This will panic!
myMap["key"] = 42Always check if a map is nil before adding keys:
if myMap == nil {
myMap = make(map[string]int)
}
myMap["key"] = 42 // Now this is safeTry it yourself
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
// Read input
var numOpsStr string
var operationsStr string
fmt.Scanln(&numOpsStr)
fmt.Scanln(&operationsStr)
// Declare maps without initialization (they will be nil)
var scores map[string]int
var grades map[string]int
// Split operations by comma
operations := strings.Split(operationsStr, ",")
// TODO: Write your code below
// Process each operation sequentially
// Handle "check", "init", and "add" operations
// For add operations, use strconv.Atoi() to convert value string to integer
// Output final state of both maps
// Check if maps are nil or initialized and print accordingly
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors