Go Variadic Function

1. Introduction

Variadic functions are an essential feature in Go, allowing you to pass an arbitrary number of arguments to a function. This can be particularly useful when you don't know beforehand how many values you need to process. In this post, we'll dive into creating and using a variadic function in Go.

Definition

A variadic function accepts a variable number of arguments of the same type. In Go, this is indicated by an ellipsis ... preceding the parameter's type. Within the function, these arguments are accessible as a slice of the specified type.

2. Program Steps

1. Define a variadic function that can take any number of integer arguments.

2. The variadic function will calculate the sum of all the integers passed to it.

3. Define the main function as the program's entry point.

4. Call the variadic function with a different number of arguments each time.

3. Code Program

package main

import "fmt"

// sum takes a variadic integer argument and returns the sum of all numbers.
func sum(numbers ...int) int {
	total := 0
	for _, number := range numbers {
		total += number // Add each number to total
	}
	return total
}

func main() {
	// Call sum with a different number of arguments
	fmt.Println("Sum of 1, 2: ", sum(1, 2))
	fmt.Println("Sum of 1, 2, 3, 4, 5: ", sum(1, 2, 3, 4, 5))
	fmt.Println("Sum of no arguments: ", sum())
}

Output:

Sum of 1, 2:  3
Sum of 1, 2, 3, 4, 5:  15
Sum of no arguments:  0

Explanation:

1. package main defines the package for the Go program.

2. import "fmt" includes the Format package necessary for output formatting.

3. The sum function is declared as variadic with ...int indicating it can take any number of int arguments.

4. Within the sum function, total is initialized to 0.

5. A for loop iterates over the slice of integers given as input to the function. The _ is the blank identifier, used because the index of the slice is not needed.

6. Each number in the range loop is added to the total, calculating the sum of all arguments.

7. The sum function returns the final calculated total.

8. In func main(), the sum function is called three times with a varying number of arguments to demonstrate the variadic feature.

9. The fmt.Println function outputs the results of the calls to sum to the console.


Comments