create a slice with a length in go

To create a slice with a specific length in Go, you can use the make function, with the second argument specifying the length of the slice. Here's an example:

main.go
mySlice := make([]int, 5) // creates a slice with length 5
59 chars
2 lines

In this example, the make function creates a slice of integers with a length of 5.

You can also assign values to specific indexes of the slice using standard array syntax:

main.go
mySlice[0] = 1
mySlice[1] = 2
mySlice[2] = 3
mySlice[3] = 4
mySlice[4] = 5
75 chars
6 lines

This creates a slice with the length of 5, and populates each element with the corresponding number.

related categories

gistlibby LogSnag