dynamic number of arguments

77 views
Skip to first unread message

yvon...@outlook.com

unread,
Mar 19, 2020, 8:21:44 PM3/19/20
to golang-nuts
Hi,

I have an array and the length of this array is dynamic. I want to pass this array's values as a list of parameters to a function. Can you please suggest what is a good way to do this?


For example,  func(query string, args ...interface{}). My array is arrayExample := []string {"1", "a", "b", "2"}. Then it will be something like func(query, arrayExample[0], arrayExample[1], arrayExample[2], arrayExample[3]).

If my array is  arrayExample := []string {"1", "a"}. Then it will be something like func(query, arrayExample[0], arrayExample[1])

But as I mentioned the array is dynamic so the length can be any number. I can get the length, but how can I pass each member in the array to the function call as a list of parameters?

Thanks a lot!

Regards,

Ian Lance Taylor

unread,
Mar 19, 2020, 8:29:20 PM3/19/20
to yvon...@outlook.com, golang-nuts
Note that what you are calling an array, Go calls a slice.

Write this as `f(query, arrayExample...)`. See
https://golang.org/ref/spec#Passing_arguments_to_..._parameters .

Ian

yvon...@outlook.com

unread,
Mar 20, 2020, 1:32:10 AM3/20/20
to golang-nuts
Thank you for the advice! It worked.
Reply all
Reply to author
Forward
0 new messages