Variadic Functions
This Go program demonstrates the use of variadic functions and the spread operator.
Output
Now, let's break down the code and explain each part:
Function Declarations:
sum(nums ...int)
: This function takes a variable number of integers using the ellipsis (...) syntax. It prints the input numbers and calculates their sum.
Main Function:
main()
: This is the entry point of the program.sum(1, 2)
: Calls thesum
function with two integer arguments (1 and 2).sum(1, 2, 3)
: Calls thesum
function with three integer arguments (1, 2, and 3).nums := []int{1, 2, 3, 4}
: Creates a slice of integers.sum(nums...)
: Calls thesum
function with the elements of thenums
slice passed as individual arguments using the spread operator...
.
Last updated
Was this helpful?