Delete Map Entries While Ranging

Delete map entries during range safely — Go skips removed entries instead of crashing — and delete() on a missing key is a documented no-op.

GoData Integrity

Code

gosnippet
35 lines
package main

import (
	"fmt"
	"slices"
)

func main() {
	sessions := map[string]int{
		"alice": 401,
		"bob":   200,
		"carol": 401,
		"dave":  200,
	}

	// 边 range 边删除是安全的:Go 保证已删除的条目不会再被产出
	for id, status := range sessions {
		if status == 401 {
			delete(sessions, id)
		}
	}
	fmt.Println("kept sessions:", len(sessions))

	// delete 删除不存在的键是空操作,不需要先检查存在性
	delete(sessions, "bob")
	delete(sessions, "ghost")

	// 与顺序无关的确定性输出:排序键后逐个打印
	names := make([]string, 0, len(sessions))
	for name := range sessions {
		names = append(names, name)
	}
	slices.Sort(names)
	fmt.Println("remaining:", names)
}

The file as it executes

Count the function main as the entire surface area of Delete Map Entries While Ranging.

Repetition is confined to for id, status := range sessions — the rest of the file is straight-line.

Using it

Running the file prints labeled results such as kept sessions:, remaining: — each operation’s effect is visible in the output.

Key statements

for id, status := range sessions {
if status == 401 {
delete(sessions, id)
}
}
for name := range sessions {
names = append(names, name)
}
names := make([]string, 0, len(sessions))

Interactive Tools for This Topic

FAQ

What does Delete Map Entries While Ranging print when run?
Running the file directly is enough — expect labeled output lines such as `kept sessions:`, `remaining:`.