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
+14.7k Golang : Find commonalities in two slices or arrays example
+7.5k Golang : Rename part of filename
+12.6k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+6.5k Golang : Spell checking with ispell example
+5.9k Unix/Linux : How to open tar.gz file ?
+6.3k Unix/Linux : Use netstat to find out IP addresses served by your website server
+11.6k Golang : Calculations using complex numbers example
+12.2k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+10.7k Android Studio : Checkbox for user to select options example
+6.8k Fix sudo yum hang problem with no output or error messages
+17.6k Convert JSON to CSV in Golang