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
+12.4k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+19.5k Golang : Measure http.Get() execution time
+15.3k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+7.9k Golang : How To Use Panic and Recover
+19.9k Golang : How to get struct tag and use field name to retrieve data?
+26.5k Golang : How to check if a connection to database is still alive ?
+10k Golang : Embed secret text string into binary(executable) file
+62.4k Golang : Convert HTTP Response body to string
+16.6k Golang : read gzipped http response
+4.5k MariaDB/MySQL : Form select statement or search query with Chinese characters
+5.5k Golang : Struct field tags and what is their purpose?
+9.8k Golang : Read file and convert content to string