0

I have 33 callback functions:

func Cb1() {} func Cb2() {} func Cb3() {} func Cb4() {} func Cb5() {} // other 28 callbacks ... 

All of them should be passed into one function. So, I did it in the most obvious way:

type fn func() func My(Cb1 fn, Cb2 fn, Cb4 fn, Cb3 fn, Cb5 fn, ... and so on ...){ Cb1() Cb2() Cb4() Cb5() } My(Cb1, Cb2, Cb4, Cb3, Cb5, ... and so on ...) 

I'm sure I'm not the only one with sore eyes from the sight of this "train" of arguments.

In javascript I would just wrap them all up in a class/object and pass them as a single argument, like so:

function My(cb = {}){ cb.Cb1(); cb.Cb2(); cb.Cb4(); cb.Cb5(); } My({ Cb1, Cb2, Cb4, Cb5 }); 

But how do we do this in Go?

2
  • 2
    You could do it the same way, wrap them in a data structure like a slice, map, or struct; or you could dig into the underlying problem, because this situation really shouldn't arise in Go. It looks like you're trying to write JavaScript in Go, which is going to lead to a lot of issues and really hard to read code. Commented Nov 9, 2020 at 22:06
  • Declare function My(cb...func()) {} Commented Nov 9, 2020 at 22:27

1 Answer 1

1

To expand upon Burak Serdar's comment above, I would suggest Variadic functions arguments.

This would give you a "My" function like the following:-

// My invokes the supplied list of callbacks func My(cbs ...func()) { for _, cb := range cbs { cb() } } 

You can see this and run it here: https://play.golang.org/p/P3xDYN-1C7M

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.