实现说明
new 与 make 的分配语义可以归结为函数 main。
使用要点
- 直接运行文件,输出会带上标签,比如
new(int) dereferenced:、slice:、new(map) inner is nil:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「new 与 make 的分配语义」会打印什么?
整个文件跑完,输出行以 new(int) dereferenced:、slice:、new(map) inner is nil: 这类前缀开头。
核心语句
items := make([]string, 0, 4)
users := make(map[string]int)
updates := make(chan int, 2)
代码示例
package main
import "fmt"
func main() {
// new(T): allocates zeroed storage and returns a pointer; works for any type
counter := new(int)
fmt.Println("new(int) dereferenced:", *counter)
// make: only for slices, maps, and channels; returns an initialized value ready for writes
items := make([]string, 0, 4)
users := make(map[string]int)
updates := make(chan int, 2)
items = append(items, "a")
users["ada"] = 1
updates <- 7
fmt.Println("slice:", items, "map:", users, "chan len:", len(updates))
// new(map[string]int) yields a pointer to a nil map: make it first before writing
ptr := new(map[string]int)
fmt.Println("new(map) inner is nil:", *ptr == nil)
}