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!
-
2Please take the tour of go to learn the basics of the language, slices are covered right after arrays.Marc– Marc2020-09-11 19:55:35 +00:00Commented Sep 11, 2020 at 19:55
Add a comment
|
3 Answers
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.