resources

slices : https://go.dev/blog/slices-intro

written by AI

Arrays and Slices in Go Programming Language

In Go programming language, arrays and slices are used to store collections of elements.

Arrays

An array is a fixed-size sequence of elements of the same type. The syntax to declare an array in Go is as follows:

var arrayName [size]dataType

Here, arrayName is the name of the array, size is the number of elements in the array, and dataType is the type of elements.

For example, let's declare and initialise an array of integers:

var numbers [5]int
numbers = [5]int{1, 2, 3, 4, 5}

In the above example, we declare an array named numbers of size 5 and initialize it with integers.

Slices

A slice is a dynamically-sized, flexible view into the elements of an array. The syntax to declare a slice in Go is as follows:

var sliceName []dataType

Here, sliceName is the name of the slice, and dataType is the type of elements.

For example, let's declare and initialize a slice of strings:

var names []string
names = []string{"Alice", "Bob", "Charlie"}