What does make do and what is the initial value of a variable?

It’s a question about “make”.
In c++ language, pointer variables are variables present in stacks, internally pointing to heap address, and allocate using keyword “new” or function “malloc()”. Is this the same concept?

P.S I’m so sorry to mentioning c++ repeatedly on “GO Forum”. I’m used to c++, so there’s a lot of confusion in accepting go lang. I can’t speak English well either, so c++ is the only way to explain my thoughts. I ask for your understanding.


    var z []int // create variable ?
    z = make([]int,0, 5) // allocate ??? or referring to new slice object ???


char * z = nullptr;  // create pointer variable, z points to nullptr
z = new char[5]; // allocate , z points to this heap address(sizeof(char) * 5)

As usual, the Go Programming Language Specification has this information:

The built-in function make takes a type T , which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T ). The memory is initialized as described in the section on initial values.


When storage is allocated for a variable, either through a declaration or a call of new , or when a new value is created, either through a composite literal or a call of make , and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.


You can’t compare those concepts directly, as in c++ you are creating an array, while in go you have a slice.

Even though the slices implementation is baked by an array, it’s not the same. An array in either go and c++ is a continuous reserved space of memory.

A slice in go adds some metadata on top of the array. Its similar to a struct, which has a a pointer to the baking array, an integer describing current site of the baking array (called capacity) and the actual count of values in the slice.

It’s the same concept as a std::vector in C++ if I understood the results of my quick web search correctly.



This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.