Sitemap
Business and Technology  (Espanol)

Data Science, Machine Learning, Conversión Digital y Negocios en Español

The dot dot dot … in GO (Golang)

2 min readApr 14, 2020

--

Variadic functions parameters

This function supposes to replace fmt.Println in order to print only when the global variable Debug is true

func DPrintf(format string, str ...interface{}) (n int, err error) {
if Debug {
n, err = fmt.Printf(format, str...)
}
return n, err
}

In this case, the function receives a variable number of parameter of any type (interface{}). A parameter type prefixed with three dots (…) is called a variadic parameter.

a ...interface{} is equivant to a []interface{}

The difference is how you pass the arguments to such a function. It is done either by giving each element of the slice separately, or as a single slice, in which case you will have to suffix the slice-value with the three dots.

In fact, the arguments can be accessed this way:

for _, s := range str {
fmt.Println(s)
}

Arguments to variadic functions

In the above function DPrintf, arguments must be passed as a list of elements separated by commas. There is a way to “unapck” the slice and pass it as a valid argument using …

toBePrinted := []int{2, 4, 8, 16}
fmt.Println(Sum(toBePrinted...))

Array literals

… notation specifies a length equal to the number of elements in the literal. So you can start enumerating values in the array without taking care about how many of them you put into it.

greeks := [...]string{"alpha", "beta", "gamma", "delta"} 
// len(greeks) is 4

The append Case

The function append has a signature like this:

func append(where []T, what ...T)

so it can be called with one or two arguments

append(slice, 'a') // one argument
append(slice, 'b', 'c') // two arguments

then, if you want to append a lot of things that are stored in a slice, … should be used in order to accomplish the task.

append(slice, []byte{'a', 'b', 'c'}...)

--

--

Business and Technology  (Espanol)
Business and Technology  (Espanol)

Published in Business and Technology (Espanol)

Data Science, Machine Learning, Conversión Digital y Negocios en Español