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.
- func Sprintf(format string, a ...interface{}) string
- func Println(a ...interface{}) (n int, err error)
- func Printf(format string, a ...interface{}) (n int, err error)
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 mainimport ("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 argumentsPrintVariadic("Test 1", "Test 2", "Test 3", "Test 4")/*output:Test 1Test 2Test 3Test 4*/// multiple type of argument passingAnyTypeVariadic("Number 1", 1, 0.456, true)/*output:Number 1 1 0.456 true*/}
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 mainimport ("fmt")func passed(arg ...string) {// getting the first arguementf := arg[0]fmt.Println(f)/*output:Test 1*/// getting the last argumentl := 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: Golang
0 Comments:
Post a Comment
If have any queries lemme know
Subscribe to Post Comments [Atom]
<< Home