Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Go Variadic Function

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Variadic functions let us define functions that take an arbitrary number of arguments. This prevents us from coding against every possible variation of the input length. In Golang, it is viable to pass a varying number of arguments of a matching style as referenced in the function signature. 

This function is best suited when you don't know the number of arguments you are passing to the function. The best sample is the built-in Println function of the fmt package, which is a variadic function.

Working of Variadic Functions

To declare a variadic function, an ellipsis "..." is given before mentioning the type of the final parameter. This displays that the function may be called with any number of arguments of this type. Let's make our own variadic function.

Example:

/*Package declaration*/
package main
import (
	"fmt"
)

/* Func find(num int, nums ...int) in the line below takes a variable number of arguments for the nums parameter. */
func find(num int, nums ...int) {
	fmt.Printf("the nums type is %T\n", nums)
	found := false

	/*  The for loop goes through the nums slice. Prints the position of num if it's there in the slice. */
	for i, v := range nums {
		if v == num {
				fmt.Println(num, " is found at index", i, "in", nums)
				found = true
		}
	}
	if !found {
			fmt.Println(num, "is not found in ", nums)
	}
	fmt.Printf("\n")
}

func main() {
	/* In the line below, the variable number of arguments to find the function are 89, 90, and 95.  */
	find(89, 89, 90, 95)
	find(45, 56, 67, 45, 90, 109)
	find(78, 38, 56, 98)
	
	/* Here we see that the last find call have only one argument */
	find(87)
}

Output:

the nums type is []int
89  is found at index 0 in [89 90 95]
 
the nums type is []int
45  is found at index 2 in [56 67 45 90 109]
 
the nums type is []int
78 is not found in  [38 56 98]
 
the nums type is []int
87 is not found in  []

Explanation:

In the program, as mentioned in the first comment above, func find(num int, nums ...int) takes in a variable number of arguments for the nums parameter.  We see that inside the function find, the type of nums is []int, an integer slice.

Here we can see the way variadic functions work. It is by transforming the variable number of arguments to a slice of the kind of the variadic parameter. For example, following another comment in the find functions of the program,we see that the variable number of arguments to the find function are 89, 90, and 95. The find function anticipates a variadic int argument. Therefore these three arguments are changed by the compiler to a slice of type int []int{89, 90, 95}, and then they are handed to the find function.

Looking at the for loop, we see that it goes through the nums slice. Prints the position of num if it's there in the slice. If not there, it prints that the number is not found.

Within the above program, if we look at the last call of the find function, we see that it has only one argument. We have not passed or directed any argument to the variadic nums ...int parameter. As told earlier, this is completely legal, and in this case, nums will be a nil slice with a length and capacity of 0.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Uses of Variadic Functions

At certain times we do not know how many string arguments will be needed for our functions. This is the point where variadic functions come into play. 

Variadic functions let us define functions that take an arbitrary number of arguments. This prevents us from coding against every possible variation of the input length.

This concept transfers across many different languages, such as Python and Java.

Example:

package main

import (
	"fmt"
)

func myVariadicFunction(args ...string) {
		fmt.Println(args)
}

func main() {
myVariadicFunction("hello", "world")
}

Command:

$ go run main.go

Output:  

[hello world]

 Note: If we try to run this, we should see our call to ‘fmt.Println()’ will print an array of strings which include ‘hello’ and ‘world’.

Variadic Functions are not limited to strings. We can also use any variation of composite or basic types.

In another example below, we will see how we are going to print s[0], the first and s[3], the fourth argument value that is passed to variadicExample() function.

Example:

package main

import "fmt"

func main() {
		variadicExample("red", "blue", "green", "yellow")
}
func variadicExample(s ...string) {
		fmt.Println(s[0])
		fmt.Println(s[3])
}

Output:

red
yellow
 

One requires being precise when running an empty function call. If the code inside of the function expects an argument and the absence of an argument will generate an error "panic: run-time error: index out of range". In the above example, you have to pass at least 4 arguments.

Multiple Arguments

The parameters accept an infinite number of arguments. The tree-dotted ellipsis tells the compiler that this string will accept from zero to multiple values.

Example:

package main
import "fmt"

func main() {
		variadicExample()
		variadicExample("red", "blue")
		variadicExample("red", "blue", "green")
		variadicExample("red", "blue", "green", "yellow")
}

func variadicExample(s ...string) {
		fmt.Println(s)
}

Output:

[]
[red blue]
[red blue green]
[red blue green yellow]

In the above example, the function has been called with single and multiple arguments; and without passing any arguments.
Uses of Variadic Function:

  • The variadic functions are usually used for string formatting. 
  • One can also pass multiple slices in the variadic function. 
  • You can not use the variadic parameter as a return value, but you can return it as a slice.

Frequently Asked Questions

How is the declaration of the variadic function made?

In declaring the variadic function, the last parameter type is preceded by an ellipsis, i.e., (…). It shows that the function can be called at any number of parameters of this type.

How does “…type” behave inside the function?

Inside the function …type behaves and acts like a slice. For example, if we have a function signature, that, add( b…int)int, is now the parameter of type[]int.

Can an existing slice be passed in a variadic function?

One can also pass an existing slice in a variadic function. As expressed in the example, we pass a slice of the total array to the function.

What happens when one does not pass any argument in the variadic function?

When one does not pass any argument in the variadic function, then the slice inside the function is nil.

Can multiple slices be passed in the variadic function?

Yes, One can also pass multiple slices in the variadic function.

Can the Variadic parameter be used as a return value?

One can not use the variadic parameter as a return value, but you can return it as a slice.

When are the times when we use a Variadic function?

• Variadic function is used when one wants to pass a slice in a function.

• The variadic functions are commonly used for string formatting.

• Variadic function is used when one doesn't know the number of parameters.

How does using variadic function affect the readability of the program?

When you use the variadic function in your program, it increases the readability of your program.

Conclusion

In this blog, we have successfully covered the variadic functions in Golang. We also discussed what variadic functions are and how they can be used in your Go programs. We have also covered some examples for better understanding.

Refer to our courses and practice questions on Coding Ninjas Studio. You can also check out some other blogs on dynamics of Golang to follow.

Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
2.
Working of Variadic Functions
2.1.
Example:
2.2.
Output:
2.3.
Explanation:
3.
Uses of Variadic Functions
3.1.
Example:
3.2.
Command:
3.3.
Example:
3.4.
Output:
4.
Multiple Arguments
4.1.
Example:
4.2.
Output:
5.
Frequently Asked Questions
5.1.
How is the declaration of the variadic function made?
5.2.
How does “…type” behave inside the function?
5.3.
Can an existing slice be passed in a variadic function?
5.4.
What happens when one does not pass any argument in the variadic function?
5.5.
Can multiple slices be passed in the variadic function?
5.6.
Can the Variadic parameter be used as a return value?
5.7.
When are the times when we use a Variadic function?
5.8.
How does using variadic function affect the readability of the program?
6.
Conclusion