Arrays without fixed length in golang

Viewed 4396

I have recently started with golang and was working with arrays and came across a situation where I did not have the number of elements. Is there a way to initialize a array without a size and then append elements in the end? Something like there in other programming languages like c++, javascript where there are vectors and arrays that can be used and we can add elements by functions like push_back or push. Is there a way that we can do this or is there a library in which we can do this? Thank you!

3 Answers
a := []int{}
a = append(a, 4)
fmt.Println(a)

You can use slice for your purpose.

array := make([]int, 0)
array = append(array, 1)
array = append(array, 2)

Here, array is a slice of int type data and initially of size 0. You can append int type data by append(array, <int-type-data>).

With Golang, Arrays always have a fixed length:

In Go, an array is a numbered sequence of elements of a specific length.

(Source: https://gobyexample.com/arrays)

If you want the flexibility of a variable length, you'll probably want to use a Slice instead:

Slices are a key data type in Go, giving a more powerful interface to sequences than arrays.

(Source: https://gobyexample.com/slices)

This post on the go blog (though old) has a nice overview of the two data types.

Related