Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

MyFunc(myArgs...)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading