Why are make() and new() functions needed in Go and what is the difference between them?
Hello everyone! I just started learning Go and got confused about two built-in functions — make() and new(). The documentation says both allocate memory, but I don't understand when to use which.
Here's a simple example that confuses me. I want to create a map and a slice:
\n\n// Option 1: with new()\nm := new(map[string]int)\ns := new([]int)\n\n// Option 2: with make()\nm2 := make(map[string]int)\ns2 := make([]int, 5)\n\nThe first option compiles, but when I try to add a value to the map using m["key"] = 1 I get panic: assignment to entry in nil map. With the slice it's also bad — s[0] = 10 crashes with nil pointer. But the second option works perfectly.
What's the magic here? Why does new()
No answers yet.
Log in to leave an answer
Blogs