Friday, 3 May 2019

Go language: Variadic Functions


A function that takes variable number of arguments is called variadic functions. You can declare a variadic function using three dots (…).

For example below function takes any number of strings as argument.
func sayHello(names ...string){

}

For example, below statements are valid
sayHello("Sibi")
sayHello("Mavra", "Sunil")
sayHello("Ram", "Krishna", "Chamu", "Sowmya")

HelloWorld.go
package main

import "fmt"

func main() {

 sayHello("Sibi")
 sayHello("Mavra", "Sunil")
 sayHello("Ram", "Krishna", "Chamu", "Sowmya")

}

func sayHello(names ...string){
 for _, value := range names{
  fmt.Println("Hello, ", value)
 }
}


Output
Hello,  Sibi
Hello,  Mavra
Hello,  Sunil
Hello,  Ram
Hello,  Krishna
Hello,  Chamu
Hello,  Sowmya

Note
a.   Variable number of arguments of a function must be defined at last.






Previous                                                 Next                                                 Home

No comments:

Post a Comment