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

Here, we are going to learn how to pass a slice of integers in a variadic function in Golang (Go Language)?
Submitted by Nidhi, on March 26, 2021 [Last updated : March 03, 2023]

How to pass a slice of integers in a variadic function in Golang?

Problem Solution:

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

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 code to pass a slice of integers in a variadic function

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

Golang Variadic Function Programs »





Comments and Discussions!

Load comments ↻





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