-2

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.

OmerMichleviz
  • 93
  • 1
  • 6

2 Answers2

0

Return a function that gets the first value from the the enclosing scope and the second number from an argument.

func Add(a int) func(int) int {
    return func(b int) int {
        return a + b
    }
}

fmt.Println(Add(3)(5)) // prints 8

None of this is idiomatic. The idiomatic code is 3 + 5.

-1

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.

Nick Bailey
  • 3,078
  • 2
  • 11
  • 13