Advertisement
In the previous blog, we learned about Functions in Golang. In this blog, we are going to have a look at Variadic Arguments in Golang Function.
Golang Variadic Arguments
Sometimes we don’t know how much parameters will be passed and then comes Variadic Parameters in Golang.
Condition for Variadic Argument:
- Variadic Arguments should only be one and must be placed at last.
- It is taken as Golang Slice, and Slice operations can be done on it.
Variadic Arguments Syntax:
JavaScript also has this functionality and there it’s called Rest Parameters.
Example in JavaScript of Rest Parameter:
function sum(...s) {
return s.reduce((previous, current) => {
return previous + current;
});
}
console.log(sum(1, 2, 3));
console.log(sum(1, 2, 3, 4));
Output:
6
10
Variadic Arguments Example:
func sum(s ...int) {
sum := 0
for _, v := range s {
sum += v
}
fmt.Println("Sum is :", sum)
}
func main() {
sum(1, 2, 3, 4)
sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
}
Output:
Sum is : 10
Sum is : 55
Learn more about Variadic Arguments from the official Documentation.
About Author
0
0
votes
Article Rating