'Adding two numbers with callback funciton [duplicate]
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 1:[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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick Bailey |
| Solution 2 |
