There are two built-in function in Go to allocate the memory new() and make() both works on different type and do different work. Knowing the difference between is must to write the clean code.
1. What new() function does and where to use ?
It only allocates zeroed memory but does not initialize the memory. It returns the pointer(address) to the allocated memory.
var price1 *int
price2:= new(int)both price1 and price are of similar type but price2 has allocated zeroed memory but price1 is not having any memory.
type Car struct {
Type string
Number string
}
func main() {
car1 := new(Car)
car2 := &Car{}
fmt.Println(car1)
fmt.Println(car2)
}car1 and car2 is of similar type, we can conclude that
2. What make() function does and where to use ?
It is used to allocated the memory and initalize int internal data structure needed for the map, channel, slices and returns the value of these type.
s := make([]int, 10, 15)
m := make(map[string]int)
c := make(chan int, 5)3. Comparison
s := make([]int, 10, 15) // Creates a slice with length 10 and capacity 15
p := new([]int) // Allocates memory for a slice pointer, but the slice is nil
fmt.Println(*p) // Prints []
*p = make([]int, 10, 15) // To initialize the slice pointed by p, you'd need to use make
fmt.Println(*p) // Prints [0 0 0 0 0 0 0 0 0 0] 5. Conculsion
We can conlude that new() is more generic while make() can be used only for the map, slices and channels.

