Golang : automatically figure out array length(size) with three dots
In Go, you can specify a length(size) of an array either explicitly or implicitly(i.e let the compiler figure out) with the three dots [...]
.
However, before we proceed further, it is good to know the tiny difference between array and slice.
Arrays length are fixed during run time. Slices are not bounded by their length and values from one slice can be passed to another even when their lengths are different.
These are ARRAYS
// Explicit length. You specified it
var days := [7]string { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }
// Implicit length with the three dots. (Compiler will determine the length)
var days := [...]string { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }
This is a SLICE
var days := []string { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }
The three dots [...] can be useful in situation when you wanted to create an array based on content from files or streams, but do not know the length until run time.
Hope this simple tutorial can be useful to you.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+19.5k Golang : How to count duplicate items in slice/array?
+1.9k Linux/MacOSX : How to symlink a file?
+3.7k Golang : Load ASN1 encoded DSA public key PEM file example
+7.1k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+2.2k Golang : How to execute code at certain day, hour and minute?
956 Golang : How to pass data between controllers with JSON Web Token
+10.3k Golang : Get all upper case or lower case characters from string example
+2.5k Golang : Handling image beyond OpenCV video capture boundary
+18k Find and replace a character in a string in Go
+2.2k Python : Print unicode escape characters and string
917 Golang : What fmt.Println() can do and println() cannot do
+1.2k Golang : Markov chains to predict probability of next state example