Passing argument based on condition

I have a function that accepts varargs.

func MyFunc(strs ...string)
MyFunc(entry1, entry2, entry3)

My usecase is to pass one of the entry based on some condition.

Is it possible to have something like this with similar effect as below (so that I don’t need to have an if-else calling MyFunc inside both):

MyFunc(entry1, if(condition)entry2, entry3)

>Solution :

Just prepare arguments as slice:

myArgs := []string{"entry1"}
if (condition) {
    myArgs = append(myArgs, "entry2")
myArgs = append(myArgs, "entry3")

and then call variadic function using your slice:


Leave a Reply