AppDividend
Latest Code Tutorials

Golang Slice make() Function | How To Create Slice in Go

0

Golang slice make() is an inbuilt function that is used to create a slice. If you want to create dynamically-sized arrays, then use the make() function. The make() function allocates a zeroed array and returns a slice that refers to that array.

Golang Slice make()

Golang make() function takes three arguments and those are type, length, and capacity. Here, capacity value is optional. The function assigns the underlying array with a size that is equal to the given capacity and returns the slice, which refers to the underlying array.

The make() function is used to create the empty slice. Here, the empty slices are those slices that contain the empty array reference.

Syntax

func make([]T, len, cap) []T

Golang slice is the flexible and extensible data structure to implement and manage the collections of data. Slices are made up of multiple items, all of the same type.

The slice is a segment of dynamic arrays that can grow and shrink as you see fit.

Golang slice make() example

Now, let’s create an empty slice.

// hello.go

package main

import "fmt"

func main() {

	// Creating an array of size 6
	// and slice this array  till 3
	// and return the reference of the slice
	// Using make() function
	var sliceA = make([]int, 3, 6)
	fmt.Printf("SliceA = %v, \nlength = %d, \ncapacity = %d\n",
		sliceA, len(sliceA), cap(sliceA))

	// Creating another array of size 6
	// and return the reference of the slice
	// Using make() function
	var sliceB = make([]int, 6)
	fmt.Printf("SliceB = %v, \nlength = %d, \ncapacity = %d\n",
		sliceB, len(sliceB), cap(sliceB))
}

Output

SliceA = [0 0 0],
length = 3,
capacity = 6
SliceB = [0 0 0 0 0 0],
length = 6,
capacity = 6

When you use make() function, one option you have is to specify the length of the slice. When you just specify the length, the capacity of the slice is the same. In our example, we have defined the length and capacity of the slice.

The length of the slice is in the first example 3, and the capacity is 6. In the second example, the length is 6, and the capacity is also 6.

Golang slice literal

You can create a slice using a slice literal. The creation of the slice literal is just like an array literal, but with one difference, you are not allowed to specify the size of the slice in the square braces[].

var sliceA = []string{"Gandia", "Arturo", "Alicia"}

One thing to remember that when you create the slice using a string literal, then it first creates the array, and after that, return the slice reference to it.

Conclusion

We can create a slice using Golang make() function and slice literal.

Finally, Golang Slice make() Function example is over.

See also

How to convert slice to string

Golang slice append()

Golang string to rune

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.