ADVERTISEMENT
ADVERTISEMENT

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

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



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.