Monday, August 17, 2015

Variadic - Functions with Variable Arguments

What are Variadic Functions?


A variadic function is one that can accept zero or more arguments for its last (or only) parameter. Such functions are indicated by placing an ellipsis (...) immediately before the type of the last or only parameter.

--Source: Programming in Go by Mark Summerfield.

Example: fmt.Println() is a variadic.


If you're a beginner, before you proceed, you can read my post about the Introduction of Functions in Go

An example is better than any explanation. See the following code sample and its output. In the code we've a function named classify that takes variable (arbitrary) number of string arguments (letters) and determines whether the letter is a vowel or consonant.

Note: Variadic functions receive the arguments as a slice of the type i.e. in below case it is string.


package main

import "fmt"

func classify(l ...string) {

 fmt.Println(l)

 for _, l := range l {

  switch l {

  case "A":
   fmt.Println("A vowel as in Apple")

  case "E":
   fmt.Println("E vowel as in Elephant")

  case "I":
   fmt.Println("I vowel as in Ice")

  case "O":
   fmt.Println("O vowel as in Ox")

  case "U":
   fmt.Println("U vowel as in Umbrella")

  case "Y":
   fmt.Println("Y as in Cry is a vowel. Y in Yellow is a consonant")

  default:
   fmt.Println(l + " consonant")

  }
 }

}

func main() {

 //Pass arbitrary number of string arguments
 classify("A", "B")
 classify("D", "E", "F")

       //Pass arbitrary number of arguments using Slices
 alphabet := []string{"A", "B", "C", "D", "E", "F", "G", "X", "Y", "Z"}
 alpha := alphabet[:2]

 classify(alpha...) //Note the way slice arg is passed using ...
 alphabet = alphabet[7:]
 classify(alphabet...)
}


Output





Please share if you liked this.

No comments:

Post a Comment