in

Go – Variadic Functions

I hadn’t come across this concept in previous languages I worked in.  In Go, however, this concept came up in an online course I was taking on Udemy.com (from Todd McLeod.)  He raised the concept of a Variadic Function.

Variadic Functions

These are functions which take an unspecified amount of parameters.  In a regular function you would lock down what parameters are allowed (how many and of what types.)  In a Variadic Function, you use “…” notation to allow for an undefined amount values to get passed.

Languages Using Variadic Functions

Go is not the only language to use Variadic Functions.  Other languages that make use of this (even using the same triple dot notation) are:

  • C++
  • Java
  • JavaScript

Python and Ruby also make use of this concept, although with a different notation (the asterisk.)

Examples of Variadic Functions in Go

Here’s some code showing a variadic function in Golang:

package main
import "fmt"

func main(){
	variadicsf("Brian", "Austin", "Lisa", "Travis", "Dan")
}

func variadicsf(names ...string){
	fmt.Println(names)

	for _, name := range names {
		fmt.Println(name)
	}
}

// The Variadic function allows for multiple params to be passed in.
// Notation of this is in the form of ...
// These params are put into an array.
// Also note the for loop making use of a blank identifier (the underscore)
// The blank identifier allows me to ignore the key of the array and only concern myself with the value.

I the above example, the code will output the collection/array (fmt.Println(names)) as well loop through the array and output each name passed in.  Here’s the outuput:

[Brian Austin Lisa Travis Dan]
Brian
Austin
Lisa
Travis
Dan

Other Variadic Forms

It is possible to have a variable function and you want to pass into it data from a slice.  The data could be like this (taken from Todd McLeod’s course): data := []float64{43, 24,10,24,33,54}

That data can not simply be passed into a variadic function.  Instead, the call to the function needs to be modified like so:

multip(data…)

func multip(num …float64){ }

What is occurring in this situation is that the call to the method is using a variadic parameter (triple dots appended to the param.)  This sends each element to the function, one at a time.  So first 43 is sent into the multip function, then 24, then 10 and so on.

 

For more info on these topics, check out Todd McLeod’s course: Learn to Code using Go

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by Admin

I work for a Telecom company writing and testing software. My passion for writing code is expressed through this blog. It's my hope that it gives hope to any and all who are self-taught.

Go – Reversing a String

Go Basics – Defer