create an array in go

To create an array in Go, you can use the following syntax:

main.go
var arrayName [size]dataType
29 chars
2 lines

Here, arrayName is the name you give to the array, size is the number of elements in the array, and dataType is the data type of each element in the array.

For example, to create an array of integers with 5 elements, you can use the following code snippet:

main.go
var numbers [5]int
19 chars
2 lines

You can also initialize the array with values at the time of declaration using the following syntax:

main.go
var arrayName = [size]dataType{value1, value2, ..., valueN}
60 chars
2 lines

For example, to create an array of integers with 3 elements containing the values 1, 2, and 3, you can use the following code snippet:

main.go
var numbers = [3]int{1, 2, 3}
30 chars
2 lines

Note that once an array is created, its size cannot be changed. If you need a more flexible data structure, consider using slices instead.

related categories

gistlibby LogSnag