Golang : Accept any number of function arguments with three dots(...)
There are times when we need to create functions that are able to accept any number of arguments(a.k.a trailing arguments) during runtime. In Golang, this can be achieved with the three dots or better known as the variadic parameter. For instance, to calculate average value of a given range of numbers. Instead of hard coding the number of arguments to be accepted, you can make your function to be more robust and accept multiple arguments during run time.
For example:
package main
import (
"fmt"
)
func avg(rest ...float64) float64 { //<----- here!
sum := 0.0
for _, num := range rest {
sum += num
}
return float64(sum) / float64(len(rest))
}
func main() {
fmt.Printf("%0.2f\n", avg(1, 2))
fmt.Printf("%0.2f\n", avg(1, 2, 3, 4, 5, 6, 7, 8, 9))
fmt.Printf("%0.2f\n", avg(99, 98, 87, 110, 121, 2))
}
Output:
1.50
5.00
86.17
Another example to accept any number of string arguments to make a new slice:
package main
import (
"fmt"
)
func makeSlice(elements ...string) []string {
var strSlice []string
for _, str := range elements {
strSlice = append(strSlice, str)
}
return strSlice
}
func main() {
fmt.Println(makeSlice("abc", "def"))
fmt.Println(makeSlice("abc", "def", "ghi"))
fmt.Println(makeSlice("abc", "def", "xyz", "123"))
fmt.Println(makeSlice("abc"))
}
Output:
[abc def]
[abc def ghi]
[abc def xyz 123]
[abc]
Happy coding!
References:
http://stackoverflow.com/questions/19238143/does-golang-support-arguments
See also : Golang : automatically figure out array length(size) with three dots
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
+17.5k How to enable MariaDB/MySQL logs ?
+13.4k Golang : How to get year, month and day?
+11.8k Golang : How to parse plain email text and process email header?
+7.2k Golang : Accessing dataframe-go element by row, column and name example
+11.8k Golang : Convert decimal number(integer) to IPv4 address
+5.8k Golang : Extract unicode string from another unicode string example
+18.8k Golang : Padding data for encryption and un-padding data for decryption
+26.7k Golang : Force your program to run with root permissions
+27.4k PHP : Convert(cast) string to bigInt
+10.4k Golang : Select region of interest with mouse click and crop from image
+5.5k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+7.6k Golang : Test if an input is an Armstrong number example