Adding two numbers with callback funciton

Issue

What is the idiomatic approach for adding two numbers in this kind of manner
Add(5)(3) -> This is done in C# with delegate but I’m not sure what the right way to do that in Go since there’s no delegate.

Solution

The idiomatic way to do that in Go is not to do that.

Go’s emphasis on performance and procedural nature means that functional patterns like currying are strongly anti-idiomatic. The only idiomatic way to add two numbers is Go is:

sum := 5 + 3

You could implement it with a function returning a function

func Add(val int) func(int) int {
    return func (other int) int {
        return val + other
    }
}

But you shouldn’t. It adds complexity and slows down your program without any befit.

Answered By – Nick Bailey

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.