Sobes.tech
Junior — Middle

Kas saaksite selgitada Make funktsiooni sisemisi mehhanisme?

sobes.tech AI

Vastus AI-lt

In Go, the make function is used to create and initialize slices, maps, and channels. It allocates memory and returns an initialized object of the required type.

Internally, make:

  • Allocates memory for the data structure and internal buffers.
  • Initializes service fields (e.g., length and capacity of the slice).
  • For slices, allocates an array with the specified capacity, returning a slice with the specified length and capacity.
  • For maps, creates a hash table with the initial size.
  • For channels, creates a buffer with the specified capacity.

Example:

s := make([]int, 5, 10) // slice of length 5, capacity 10
m := make(map[string]int, 10) // map with initial capacity 10
ch := make(chan int, 5) // channel with buffer of 5 elements

Thus, make is an built-in mechanism for creating and initializing complex data types, different from new, which only allocates memory without initialization.