9

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!

1
  • 2
    Please take the tour of go to learn the basics of the language, slices are covered right after arrays. Commented Sep 11, 2020 at 19:55

3 Answers 3

20
a := []int{}
a = append(a, 4)
fmt.Println(a)
Sign up to request clarification or add additional context in comments.

Comments

8

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>).

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.