ADVERTISEMENT
ADVERTISEMENT

Golang program to demonstrate the variadic function

Here, we are going to demonstrate the variadic function in Golang (Go Language).
Submitted by Nidhi, on March 26, 2021

Problem Solution:

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

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.

Golang Variadic Function Programs »



ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.