×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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 [Last updated : March 03, 2023]

Variadic function in Golang

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 code to implement the variadic function

// 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 »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.