← 中文资源

简体中文版本

clear 内建清空 map 与切片

clear 内建函数一行清空 map 的全部键;对切片则把每个槽位写回零值且保留长度与容量;对 nil 的 map 或切片是无害空操作。

阅读英文原文

实现说明

clear 内建清空 map 与切片以函数 main为骨架。

使用要点

  • 跑完文件,输出里会留下标记——map len after clear:、orders present:、slice after clear:。

常见问题

运行「clear 内建清空 map 与切片」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 map len after clear:、orders present:、slice after clear: 标签标明各步骤。

核心语句

counts := map[string]int{"orders": 3, "billing": 1, "auth": 9}

代码示例

package main

import "fmt"

func main() {
	// the clear builtin resets a map: every key is deleted in one call
	counts := map[string]int{"orders": 3, "billing": 1, "auth": 9}
	clear(counts)
	fmt.Println("map len after clear:", len(counts))
	_, present := counts["orders"]
	fmt.Println("orders present:", present)

	// clear resets a slice: zero values fill every slot, len and cap stay
	buf := []int{7, 8, 9}
	clear(buf)
	fmt.Println("slice after clear:", buf, "len:", len(buf), "cap:", cap(buf))

	// on nil maps and nil slices clear is a no-op, no panic
	var nilSlice []int
	clear(nilSlice)
	var nilMap map[string]int
	clear(nilMap)
	fmt.Println("nil targets cleared without panic")
}