Skip to content

Instantly share code, notes, and snippets.

@ifindev
Last active June 7, 2022 15:26
Show Gist options
  • Save ifindev/84365b3387249d426fd52f4c7677837b to your computer and use it in GitHub Desktop.
Save ifindev/84365b3387249d426fd52f4c7677837b to your computer and use it in GitHub Desktop.
Golang Basic
// Closure is a function which can be stored on a variable
package main
import {
"fmt"
}
func main() {
var numbers = []int{2, 3, 4, 5, 6, 7, 8, 9}
var getMinMax = func(n []int) (int, int) {
var min, max int
for i, e := range n {
switch {
case i == 0:
max, min = e, e
case e > max:
max = e
case e < min:
min = e
}
}
return min, max
}
min, max := getMinMax(numbers)
fmt.Println("Original data: ", numbers)
fmt.Println("Min: ", min)
fmt.Printf("Max: %d\n\n", max)
}
// IIFE --> Immediately Invoked Function Expression
// A closure which is being invoked at the time of its creation
package main
import {
"fmt"
}
func main() {
var numbers = []int{2, 3, 4, 5, 6, 7, 8, 9}
var newNumbers = func(min int) []int {
var r []int
for _, e := range numbers {
if e < min {
continue
}
r = append(r, e)
}
return r
}(4)
fmt.Println("original number : ", numbers)
fmt.Println("filtered number : ", newNumbers)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment