Go – How to Create a Variadic Functions in Golang

Hello everyone, In this tutorial, we will show you how to create simple variadic functions in golang. The following example program has been tested and shared in the same post.

How to Create a Variadic Functions in Golang.
Go – How to Create a Variadic Functions in Golang

What is the Variadic functions?

The variadic functions are a really great feature or tool for programmers and it is supported by many programming languages. Variadic functions, which can be invoked with any numbers of trailing arguments and let`s see the syntax for creating variadic functions in golang.

Syntax

func func_name(variable_name ...datatype) {
	
	// implementation
}


Creating a variadic functions in go

The below code snippet will give you an idea about, how to create variadic functions in go. What is the sum() function is doing? the sum() is function it is responsible to calculate the sum of the given numbers, which is passed as trailing arguments when it is called.

// variadic functions 
func sum(numbers ...int) int {
	
	var sum int = 0;
	
	for i := 0; i < len(numbers); i++ {
		
		sum += numbers[i]
		
	}
	
	return sum
}

Complete Example

This complete example will give you a full view for defining and invoking the variadic function in the go programming language.

package main

import "fmt"

func main()  {

	fmt.Println("Result:", sum(10)) // invoking with 1 arg
	fmt.Println("Result:", sum(10, 20)) // invoking with 2 args
	fmt.Println("Result:", sum(10, 20, 30)) // invoking with 3 args
	fmt.Println("Result:", sum(10, 20, 30, 40)) // invoking with 4 args
	fmt.Println("Result:", sum(10, 20, 30, 40)) // invoking with 5 args
}

func sum(numbers ...int) int {
	var sum int = 0;
	for i := 0; i < len(numbers); i++ {
		sum += numbers[i]
	}
	return sum
}

Output

Result: 10
Result: 30
Result: 60
Result: 100
Result: 100

References

  1. https://golang.org/doc/
  2. https://golang.org/pkg/
  3. https://golang.org/pkg/fmt/
  4. https://golang.org/pkg/fmt/#Println
  5. https://en.wikipedia.org/wiki/Variadic_function