Go make 和 new 区别

简单来说,new 只是分配了内存,make 是用于 slice,map,channel 的初始化

代码过程中很少需要使用 new,基本都是用的 make

在用 string、int 等类型,使用的时候都是直接赋值使用的

package main

import "fmt"

func main() {
	var s1 *string
	fmt.Println(s1)
	s1 = new(string) // 分配内存
	*s1 = "s1"
	fmt.Println(*s1)

	m1 := new(map[string]string) // 分配内存
	fmt.Println(m1)

	m1 = &map[string]string{"m1": "m1"}
	fmt.Println(m1)

	m2 := make(map[string]string)
	m2["m1"] = "m1"
	fmt.Println(m2)
}

new(T) 返回的是 T 的指针

// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
func new(Type) *Type

make 只能用于 slice,map,channel

// The make built-in function allocates and initializes an object of type
// slice, map, or chan (only). Like new, the first argument is a type, not a
// value. Unlike new, make's return type is the same as the type of its
// argument, not a pointer to it. The specification of the result depends on
// the type:
//
//	Slice: The size specifies the length. The capacity of the slice is
//	equal to its length. A second integer argument may be provided to
//	specify a different capacity; it must be no smaller than the
//	length. For example, make([]int, 0, 10) allocates an underlying array
//	of size 10 and returns a slice of length 0 and capacity 10 that is
//	backed by this underlying array.
//	Map: An empty map is allocated with enough space to hold the
//	specified number of elements. The size may be omitted, in which case
//	a small starting size is allocated.
//	Channel: The channel's buffer is initialized with the specified
//	buffer capacity. If zero, or the size is omitted, the channel is
//	unbuffered.
func make(t Type, size ...IntegerType) Type
上次更新:
贡献者: kongzZ