Last active
May 21, 2024 14:09
-
-
Save Tanmay451/92e5bb3e0828074a24133695dc0dcc13 to your computer and use it in GitHub Desktop.
In Go, functions are first-class citizens. This means they can be assigned to variables, passed as arguments to other functions, and returned from functions. Higher-order functions are functions that take other functions as parameters or return functions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
// Define some basic arithmetic operations as first-class functions. | |
// These functions can be assigned to variables, passed as arguments, and returned from other functions. | |
var sum = func(a, b int) int { return a + b } | |
var minus = func(a, b int) int { return a - b } | |
var multiply = func(a, b int) int { return a * b } | |
var divide = func(a, b int) int { return a / b } | |
// Higher-order function: 'calculation' takes another function 'do' as an argument. | |
// This demonstrates how functions can be passed as parameters to other functions. | |
func calculation(do func(int, int) int, a, b int) int { | |
return do(a, b) | |
} | |
func main() { | |
a := 10 | |
b := 2 | |
// Using the higher-order function 'calculation' with different operations. | |
// This showcases the flexibility and reusability of functional programming. | |
fmt.Printf("sum: %d\n", calculation(sum, a, b)) | |
fmt.Printf("minus: %d\n", calculation(minus, a, b)) | |
fmt.Printf("multiply: %d\n", calculation(multiply, a, b)) | |
fmt.Printf("divide: %d\n", calculation(divide, a, b)) | |
} | |
// Output: | |
// sum: 12 | |
// minus: 8 | |
// multiply: 20 | |
// divide: 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment