Q:

Golang program to pass a slice of integers in a variadic function

belongs to collection: Golang Variadic Function Programs

0

In this program, we will create a variadic function that will accept a slice of integers as an argument.

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 pass a slice of integers in a variadic function is given below. The given program is compiled and executed successfully.

// Golang program to pass a slice in a
// variadic function

package main

import "fmt"

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

func main() {
	IntSlice := []int{10, 20, 30, 40}
	MyFun(IntSlice...)
}

Output:

Values: 10 20 30 40

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 slice of integers and printed the elements of slice on the console screen.

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

In the main() function, we called MyFun() function with slice of integers. The MyFun() function will print the elements of the slice on the console screen.

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

total answers (1)

<< Golang program to create a function with the varia...