Go make function: create slice, map and channel

table of Contents

description

Syntax and parameters

Usage example

Create slice

Create map

Create channel

Precautions

The difference between make and new


 

description

The make function is a built-in function of Go. Its function is to initialize slice, map, or chan and return a reference. make is only used to create slices, maps, and channels, and return their instances.

 

Syntax and parameters

Function signature

func make(t Type, size ...IntegerType) Type
name meaning
t Slice, map or channel type.
size Integer type slices have different meanings when facing different types. Whether it can be omitted is related to the creation type.

Usage example

Create slice

make([]Type, len, cap)

The cap can be omitted. When cap is omitted, it is equal to len by default. In addition, the condition of cap >= len >= 0 must be established. For example, create an int type slice with both len and cap being 10.

package main

import "fmt"

func main() {
	demo := make([]int, 10)
	fmt.Println("demo:", demo)
    // output: demo: [0 0 0 0 0 0 0 0 0 0]
	fmt.Println("len(demo):", len(demo))
    // output: len(demo): 10
	fmt.Println("cap(demo):", cap(demo))
    // output: cap(demo): 10
}

 

Create map

make(map[keyType] valueType, size)

keyType represents the key type of the map, and valueType represents the value type of the map. size is an integer parameter that indicates the storage capacity of the map. This parameter can be omitted.

package main

import "fmt"

func main() {
	demo := make(map[string]int)
	fmt.Println("demo:", demo)
	// output: demo: map[]
}

 

Create channel

make(chan Type, size)

Use make to create a channel, the first parameter is the channel type. size represents the size of the buffer slot. It is an optional integer parameter greater than or equal to 0. The default size = 0. When the buffer slot is not 0, it means that the channel is an asynchronous channel.

package main

import "fmt"

func main() {
	demo := make(chan int, 10)
	fmt.Println("demo:", demo)
	// output: demo: map[]
	fmt.Println("len(demo):", len(demo))
	// output: len(demo): 0
	fmt.Println("cap(demo):", cap(demo))
	// output: cap(demo): 10
}

 

Precautions

The difference between make and new

The role of new is to initialize a pointer to the type (*T). Use the new function to allocate space. What is passed to the new function is a type, not a value. What is returned is a pointer to this newly allocated zero value.

The role of make is to initialize slice, map, or chan and return a reference (T). make is only used to create slices, maps, and channels, and return their instances.

Guess you like

Origin blog.csdn.net/TCatTime/article/details/111567560