new(T) is a built-in function in Go that allocates memory for a variable of type T, initialises it to the zero value of T, and returns a pointer to it (*T). For numeric types, this means a value of 0; for booleans, it means false; for pointers, it means nil, and so on. This allows users to allocate a data structure with new and use it without needing further initialisation. This is different from languages where new might also call a constructor or perform initialisation beyond just zeroing memory.
For example, bytes.Buffer, whose zero value is an empty buffer ready for use. The sync.Mutex, whose zero value is an unlocked mutex. This design principle eliminates the need for explicit constructors or initialisation methods for such types.
This principle applies not just to simple types but also to composite types.
type SyncedBuffer struct {
lock sync.Mutex
buffer bytes.Buffer
}
SyncedBuffer contains a sync.Mutex and a bytes.Buffer, both of which are useful in their zero value state. The SyncedBuffer can be used immediately after being allocated with new or even just declared without allocation.
p := new(SyncedBuffer) // type *SyncedBuffer
var v SyncedBuffer // type SyncedBuffer
Both instances (p and v) are ready to use without any additional setup.
new to allocate and automatically zero-initialise memory. This reduces the need for explicit constructors or initialisation methods.malloc is uninitialised and contains garbage values until you explicitly set it.In JavaScript, you explicitly define what the initial state of an object should be. There's no automatic zeroing or concept of a "useful zero value" for custom objects.
// JavaScript object initialization
const buffer = { data: [], size: 0 };
// Using the object immediately
buffer.data.push("Hello");
function Buffer() {
this.data = [];
this.size = 0;
}
const buffer = new Buffer();
buffer.data.push("Hello");
In C, memory allocation is more manual and lower level compared to Go. When you allocate memory using malloc, the memory is not initialised; it contains garbage values until you explicitly initialise it.
#include <stdlib.h>
typedef struct {
char* data;
int size;
} Buffer;
Buffer* buffer = malloc(sizeof(Buffer));
if (buffer != NULL) {
// Explicitly initialize fields in C
buffer->data = NULL; // Equivalent to Go's zero value for pointers
buffer->size = 0; // Equivalent to Go's zero value for integers
}