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.7k Android Studio : Create custom icons for your application example
+8.5k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+17.9k Golang : Iterating Elements Over A List
+21.6k Golang : Securing password with salt
+5k Golang : Intercept, inject and replay HTTP traffics from web server
+16.6k Golang : How to save log messages to file?
+51.3k Golang : How to get time in milliseconds?
+18.4k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+5.1k Golang : Shortening import identifier
+9.7k Golang : Text file editor (accept input from screen and save to file)
+11.7k Golang : List running EC2 instances and descriptions
+10.4k Golang : Replace a parameter's value inside a configuration file example