make vs new
new(T) allocates a zero T and returns *T. make creates a usable slice, map, or channel and returns that type, not a pointer. You almost never need new; you need make whenever you will write to a map or grow a slice with a known size.
Detailed Explanation
Both built-ins allocate. They answer different questions. new is "give me a pointer to a zero." make is "give me a slice, map, or channel that is ready to use." Mixing them is a common beginner mistake: new([]int) is a pointer to a nil slice, not a slice with room for elements.
new(T). It is equivalent to var v T; p := &v except the variable is anonymous. The result is *T. For a struct, new(Session) is the same as &Session{}. Prefer the composite literal; it can set fields. new shows up in generated code and in a few generic helpers. Application code can forget it exists.
make for slices. make([]int, length) gives a slice of length zeros and capacity length. make([]int, length, capacity) reserves extra room so later append does not reallocate immediately. make([]int, 0, 64) is the usual "empty but ready to append" form. A nil slice (var s []int) also appends; make matters when you know the size and want one allocation.
make for maps. make(map[string]int) or make(map[string]int, hint) creates a non-nil map. Writes to a nil map panic. The hint is a size hint, not a limit. There is no new equivalent that produces a usable map: new(map[string]int) is *map[string]int pointing at a nil map.
make for channels. make(chan int) is unbuffered. make(chan int, 8) is buffered with room for eight values. new(chan int) is a pointer to a nil channel, which is a different and usually useless thing.
What it costs. make([]T, n) zeros n elements. make([]T, 0, n) allocates room for n without zeroing them as live length. Pick the second when you will append. make(map[K]V, n) sizes buckets so the first n inserts avoid growing. Measure before you pre-size based on a guess that is off by orders of magnitude.
Code Examples
package main
import "fmt"
func main() {
s := make([]int, 0, 4)
s = append(s, 1, 2)
fmt.Println(s, cap(s)) // [1 2] 4
m := make(map[string]int, 8)
m["a"] = 1
ch := make(chan int, 1)
ch <- 7
fmt.Println(<-ch)
}func contrast() {
p := new([]int) // *[]int, pointing at nil slice
fmt.Println(*p == nil) // true
s := make([]int, 2) // []int of length 2
fmt.Println(len(s), s[0]) // 2 0
}func readySlice(n int) []int {
return make([]int, 0, n)
}Common Gotchas
`make` is only for slice, map, and channel
`make(int)` does not compile. Use `new` or a literal for other types.
Writing to a map from `new(map[K]V)` panics
you have a pointer to a nil map. Use `make`.
`make([]T, n)` vs `make([]T, 0, n)`
the first has `len == n` already filled with zeros. Appending starts after those zeros, which is rarely what you meant if you wanted "capacity n."
`&T{}` replaces `new(T)` for structs
you can set fields in the same expression.