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
+10.6k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+9k Golang : Populate or initialize struct with values example
+19.2k Golang : Execute shell command
+6.9k Golang : Pat multiplexer routing example
+31.6k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+14.4k Golang : How to convert a number to words
+8.1k Golang : Variadic function arguments sanity check example
+9.5k Golang : Extract or copy items from map based on value
+15.9k Golang : Update database with GORM example
+19.5k Golang : Fix cannot download, $GOPATH not set error
+11.2k Golang : Fix go.exe is not compatible with the version of Windows you're running