Why are make() and new() functions needed in Go? What's the difference?
Hello everyone! I started learning Go recently and I can't understand why two separate functions are needed for memory allocation: make() and new(). They both seem to create objects, but the examples from the documentation only confused me.
Here's what I'm trying to do. I want to create a slice and immediately add elements to it:
\n\npackage main\n\nimport "fmt"\n\nfunc main() {\n // Trying to create a slice via new\n slice1 := new([]int)\n fmt.Println(slice1) // Outputs: &[]\n // But how to add an element? slice1 = append(slice1, 1) doesn't work\n // Error: first argument to append must be slice; have *[]int\n\n // Trying to create a slice via make\n slice2 := make([]int, 5)\n fmt.Println(slice2) // Outputs: [0 0 0 0 0]\n // Works, but why No answers yet.
Log in to leave an answer