Menu
Coddy logo textTech

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 point

When 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"] = 42

To 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 safe

This simple check ensures your program won't crash when working with potentially uninitialized maps, making your code more robust and reliable.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create 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:

  1. Create two map variables of type map[string]int named scores and grades without initializing them (they will be nil)
  2. Process each operation from the input string sequentially:
  3. 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
  4. For "init" operations:
    • Initialize the specified map using make(map[string]int)
    • Print "Initialized map [map_name]"
  5. 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]"
  6. 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
  7. 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

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 point

Reading 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"] = 42

Always check if a map is nil before adding keys:

if myMap == nil {
    myMap = make(map[string]int)
}
myMap["key"] = 42 // Now this is safe

Try 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
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow