Wednesday 17 November 2021

Golang Variadic Function and Arguments

In the previous article we learn about how defer work in Golang and today we are going to cover the Variadic functions and Variadic arguments in golang.

Variadic Function is Golang?

In many cases, we needed multiple parameters to be passed in a function. Sometimes we know and sometimes we don't. Golang variadic function applies to the second case where we don't know how many parameters(arguments) could be passed when calling that function.

Declaration of Variadic Function

It's not hard to declare a variadic function. We use the pack operator(three dot ...) to pass an arbitrary number of arguments in function.
Syntax of variadic function
func funcName(param ...paramType) returnType {}


Some Built-in Variadic Function

There are several variadic functions we uses all the time. All of them are built-in. Let's see some of them.
  1. func Sprintf(format string, a ...interface{}) string
  2. func Println(a ...interface{}) (n int, err error)
  3. func Printf(format string, a ...interface{}) (n int, err error)
There are much more variadic functions in built-in packages as well you can checkout godoc site to get more variadic function.

When to use Variadic functions?

Obviously it's a fair question when to use the thing we are covering so the uses of the variadic functions are there when you don't have any fixed length of arguments for a function on that stage you should use the variadic function.

Creating variadic function and Passing arguments in it.

As explained variadic functions can take any number of arguments and any type of arguments. Let's checkout the code to get more info in it.

package main

import (
"fmt"
)

func PrintVariadic(names ...string) {
for i := range names {
fmt.Println(names[i])
}
}

func AnyTypeVariadic(all ...interface{}) {
fmt.Println(all...) // ... forwarding all the types data.
}

func main() {

// passing single type of arguments
PrintVariadic("Test 1", "Test 2", "Test 3", "Test 4")
/*
output:
Test 1
Test 2
Test 3
Test 4
*/

// multiple type of argument passing
AnyTypeVariadic("Number 1", 1, 0.456, true)

/*
output:
Number 1 1 0.456 true
*/

}

Run in playground 


Accessing targeted argument from variadic function.

Ok it sounds good to parse multiple parameters with single arguments declaring but what about getting specific argument which we used to provide to variadic function so let's cover this. How we can get specific argument from variadic function.

package main

import (
"fmt"
)

func passed(arg ...string) {

// getting the first arguement
f := arg[0]
fmt.Println(f)
/*
output:
Test 1
*/

// getting the last argument
l := arg[len(arg)-1]
fmt.Println(l)
/*
output:
Test 4
*/
}

func main() {
passed("Test 1", "Test 2", "Test 3", "Test 4")
}

Updating More SOON







Labels:

0 Comments:

Post a Comment

If have any queries lemme know

Subscribe to Post Comments [Atom]

<< Home