实现说明
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")
}