The GO language make of assigns usage instances

  • 2020-05-17 05:41:04
  • OfStack

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

make() allocation: the internal function make(T, args) has a different service purpose than new(T).
It generates only slices, maps, and tracks, and returns an initialized (not zero) value of type T, not *T.

The reason for this distinction is that these three types of data structures must be initialized before they can be used.
For example, a slice is a three-item descriptor containing a data pointer (in an array), length, and capacity. Before these items are initialized, the slice is nil.

For slicing, mapping, and tracing, make initializes the internal data structure and prepares the values to be used.
Remember that make() is only used for mapping, slicing, and tracing, and does not return Pointers. To be clear, the pointer is allocated using new()

package main
import "fmt"
func main() {
 // Distributed slice structure ;* p== zero
 var p *[]int = new([]int)
 *p = make([]int, 100, 100) // It's a little bit complicated to write this way, so it's easy to get confused
 fmt.Println(p)
 // You will now V distribution 1 Two new arrays, 100 An integer
 // writing 1
 //var v  []int = make([]int, 100)
 // writing 2 : a very common way of writing, concise and clear
 v := make([]int, 100)
 fmt.Println(v)
}
through make() You also have the flexibility to create array slices. Such as
// Creating slices is also used make Function, it's assigned 1 Zero groups and a slice that points to the array.
// create 1 The initial number of elements is zero 5 Array slice, the initial value of the element is 0
a := make([]int, 5)  // len(a)=5
// Slices have length and volume. The maximum length of a slice is its capacity.
// The specified 1 The volume of the slice passes through the section 3 A parameter.
// create 1 The initial number of elements is zero 5 Array slice, the initial value of the element is 0 And set aside 10 The storage space of element
b := make([]int, 5, 10)    // len(b)=5, cap(b)=10
// The sections can be increased by re-slicing.
b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:]      // len(b)=4, cap(b)=4
// Create and initialize the include directly 5 A slice of an array of elements
c := []int{1,2,3,4,5}

I hope this article has been helpful to you in the programming of Go language.


Related articles: