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
+5.1k Golang : How to deal with configuration data?
+25k Golang : Convert uint value to string type
+5.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+5.8k PHP : How to check if an array is empty ?
+16.1k Golang : Execute terminal command to remote machine example
+32.4k Golang : Regular Expression for alphanumeric and underscore
+5.9k Golang : Create new color from command line parameters
+29.5k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+15.1k Golang : invalid character ',' looking for beginning of value
+21.9k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+10.9k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+6.9k Golang : Transform lisp or spinal case to Pascal case example