Q:

Golang program to demonstrate the variadic function

0

In this program, we will create a variadic function that will accept the variable number of arguments in a function.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the variadic function is given below. The given program is compiled and executed successfully.

// Golang program to demonstrate variadic function

package main

import "fmt"

func MyFun(vals ...int) {
	fmt.Printf("\nValues: ")
	for _, val := range vals {
		fmt.Printf("%d ", val)
	}
}

func main() {
	MyFun(10)
	MyFun(10, 20)
	MyFun(10, 20, 30)
}

Output:

Values: 10
Values: 10 20
Values: 10 20 30

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.

In this program, we created a variadic function MyFun() to accept variable number of arguments.

func MyFun(vals ...int) {
    fmt.Printf("\nValues: ")
    for _, val := range vals {
      fmt.Printf("%d ",val)
    }
}

In the main() function, we called MyFun() function with different number of arguments. The MyFun() function will print passed arguments on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now