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
+16.4k Golang : File path independent of Operating System
+12.2k Golang : How to display image file or expose CSS, JS files from localhost?
+11.5k Get form post value in Go
+6.1k Apt-get to install and uninstall Golang
+10.6k Android Studio : Checkbox for user to select options example
+7.4k Golang : Rename part of filename
+9.2k Golang : How to protect your source code from client, hosting company or hacker?
+5.5k Fix fatal error: evacuation not done in time problem
+11.9k Golang : Find and draw contours with OpenCV example
+14.7k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+11.6k Golang : Gorilla web tool kit secure cookie example