Junior — Middle
Can you explain the role of the New function and how it is implemented in programming language?
sobes.tech AI
Answer from AI
In Go, the new function is used to allocate memory for a new object of a specified type and returns a pointer to that object, initialized to the zero value.
For example:
p := new(int) // p has type *int, pointing to an int with value 0
The implementation of new is built into the language and compiles to calls to the memory allocator. It does not invoke constructors but simply allocates and zeroes the memory.
Difference from make in Go:
newallocates memory for any type and returns a pointer.makeis used only for initializing slices, maps, and channels, returning an initialized value (not a pointer).
Thus, new is a low-level way of allocating memory, often replaced by literals or make for convenience and initialization.