How to pass variable length arguments as arguments on another function in Golang?

FunctionGoVariadic Functions

Function Problem Overview


How to pass variable length arguments in Go? for example, I want to call

func MyPrint(format string, args ...interface{}) {
  fmt.Printf("[MY PREFIX] " + format, ???)
}

// to be called as: MyPrint("yay %d", 213) 
//              or  MyPrint("yay")
//              or  MyPrint("yay %d %d",123,234)

Function Solutions


Solution 1 - Function

Ah found it...functions that accept variable length arguments are called Variadic Functions. Example:

package main

import "fmt"

func MyPrint(format string, args ...interface{}) {
  fmt.Printf("[MY PREFIX] " + format, args...)
}

func main() {
 MyPrint("yay %d %d\n",123,234);
 MyPrint("yay %d\n ",123);
 MyPrint("yay %d\n");
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKokizzuView Question on Stackoverflow
Solution 1 - FunctionKokizzuView Answer on Stackoverflow