For make, it'sGo languageThe functions used to allocate memory for the three data types slice, map, and chan. Because of the specificity of these three data types, the functions used to allocate and initialize these three data types are
The syntax structure of make is very simple, as shown below:
make(type, len, cap)
Some common pitfalls in using make
Using make
Attention:Slice in the make, set the size of the slice, in fact, in the slice is added len empty data, if the use of append to operate, is equivalent to the slice after the addition of new elements, the example is as follows:
The results of the run are:
Note: When using append to add elements to slice, when the length is greater than the capacity, then the slice will be expanded, the expansion principle is:
- cap :Required capacity
- :: Capacity of old slices
- newcap :the final capacity to be requested
- doublecap : twice
- When the required capacity cap is greater than twice the old capacity doublecap, we apply for the new capacity is the required capacity ... When the required capacity cap is greater than twice the old capacity doublecap, the new capacity we apply for is the required capacity.
- When the required capacity cap is less than twice the old capacity doublecap, determine whether the length of the old slice is less than 1024, if it is less than 1024, then newcap=twice the old cap, directly doubled ... When the required capacity is less than twice the old capacity doublecap, determine whether the length of the old slice is less than 1024, if less than 1024, then NewCap=twice the old, directly doubled
- When the length of the old slice >=1024, it will be repeatedly increased by 25% until the new capacity newcap exceeds the required capacity cap. where newcap > 0 is to prevent overflow of int type, if overflow then it is directly newcap = cap(the required capacity). When the length of the old slice >=1024, it will be repeatedly increased by 25% until the new capacity newcap exceeds the required capacity cap. where newcap > 0 is to prevent overflow of int type, if overflow then directly newcap = cap(required capacity).
Using make
Attention:map does not work when using make, even if you specify len, which does not act as a limit. Such as:
Results for: