SoFunction
Updated on 2025-03-05

GO language make allocation usage example

This article describes the usage of make() allocation in the GO language. Share it for your reference. The specific analysis is as follows:

make() allocation: The service purpose of the internal function make(T, args) is different from new(T).
It only generates slices, maps, and paths, and returns an initialized (not zero), type T, not *T value.

The reason for this distinction is that these three types of data structures must be initialized before use.
For example, a slice is a three-item descriptor that contains data pointers (in an array), length, and capacity; before these items are initialized, the slice is nil.

For slices, maps, and routes, make initializes the internal data structure and prepares the value to be used.
Remember make() is only used for mapping, slices, and paths, and does not return pointers. To get pointers explicitly assign them with new()

Copy the codeThe code is as follows:
package main
import "fmt"
func main() {
//Assign slice structure;* p==zero
 var p *[]int = new([]int)
*p = make([]int, 100, 100) //This writing is a bit complicated and can easily mess up
 (p)
//Now assign V a new array, 100 integers
//Writing method one
 //var v  []int = make([]int, 100)
//Writing method 2: A very common way of writing, brief description
 v := make([]int, 100)
 (v)
}
Make() also allows you to create array slices flexibly. like
//Creating slices also uses the make function, which is assigned a zero array and a slice pointing to this array.
//Create an array slice with an initial number of elements of 5, and the initial value of the element is 0
a := make([]int, 5)  // len(a)=5
//Slices have length and capacity. The maximum length of the slice is its capacity.
//Specify the capacity of a slice, passing the third parameter.
//Create an array slice with an initial number of elements of 5, the initial value of the element is 0, and reserve 10 elements of storage space
b := make([]int, 5, 10)    // len(b)=5, cap(b)=10
//Reslice the slices.
b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:]      // len(b)=4, cap(b)=4
//Directly create and initialize an array slice containing 5 elements
c := []int{1,2,3,4,5}

I hope this article will be helpful to everyone's Go language programming.