Question about syntax for assigning a function to a variable

With the code below mi.Installer = ... will be assigned the function and mi.Updater = ... will throw a compiler error. That makes sense, no problem there.

I chanced through “experimenting” on the syntax for mi.Installer = func() {a()} and it works as expected when used later so that’s good.

However, I haven’t found a definitive article saying this is the way to do it so please forgive this very rookie question… Is this syntax that I found playing a good/right way to write this or is there perhaps a better syntax?

I ask because it seems convoluted to me even though it works just fine because it looks like it’s assigning an anonymous function with the function a() inside it which seems like a wrapper function around a function which seems like an extra function call that shouldn’t be necessary.

type ModuleInfo struct {
	Installer func()
	Updater   func()

func (mi ModuleInfo) ModuleBoot() ModuleInfo {
	mi.Installer = func() {a()}
	mi.Updater = a()
	return mi

func a() {
	fmt.Println(`Hello World`)

Yes, it’s convoluted, but the empty useless function could be very well a decorator. Which would add extra behavior to you stub function related to Installer. You could also do a direct assignment mi.Updater = a which is just “renamespacing” your function. But you should seriously read Rob Pike’s approach It may seem “convoluted”, but it open really interesting venues to configurations/options.

You’re right. You’re technically assigning a wrapper that calls a, not a itself. To assign a to mi.Installer, just assign it like you would any other variable:

mi.Installer = a

That article was very interesting. Thank you! Go keeps on surprising me.

Ugh, face palm slap! Of course, just write the function without the brackets and it assigns without the convolution. Thanks.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.