Skip to content

Instantly share code, notes, and snippets.

@jqjk
Last active April 18, 2022 06:48
Show Gist options
  • Save jqjk/572a4a46a3a6e2b839af4c93d2bd92b7 to your computer and use it in GitHub Desktop.
Save jqjk/572a4a46a3a6e2b839af4c93d2bd92b7 to your computer and use it in GitHub Desktop.
package main
import "fmt"
func main() {
ptr := Ptr[bool](false)
fmt.Println(ptr)
var sum int
Apply[int]([]int{10, 20}, func(i, v int) {
sum += v
})
fmt.Println(sum) // 30
ns := []int{1, 2, 3, 4}
ms := Filter[int](ns, func(i, v int) bool {
return v%2 == 0
})
fmt.Println(ms) // [2 4]
}
func Ptr[T any](v T) *T {
return &v
}
func Apply[T any](values []T, applyer func(int, T)) {
for i, v := range values {
applyer(i, v)
}
}
func Filter[T any](values []T, filter func(int, T) bool) []T {
var result []T
for i, v := range values {
if filter(i, v) {
result = append(result, v)
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment