GoLang -- jps sasadara
Install to the Ubuntu OS
https://www.systutorials.com/how-to-install-go-1-13-x-on-ubuntu-18-04/
Guide
https://docs.google.com/document/d/1ckYpi6hcRkaBUEk975f54oGsHYHu7GhzOk7-nOrkNxo/edit#
Callback: passing a func as an argument
- Supper Example 1:
https://play.golang.org/p/AI8jKiYIKO6
- Supper Example 2:
package mainimport "fmt"func visit(numbers []int, callback func(int)) {for _, n := range numbers {callback(n)}}func main() {visit([]int{1, 2, 3, 4}, func(n int) {fmt.Println(n)})}// callback: passing a func as an argument
package main
import "fmt"
func filter(numbers []int, callback func(int) bool) []int {
var xs []int
for _, n := range numbers {
if callback(n) {
xs = append(xs, n)
}
}
return xs
}
func main() {
xs := filter([]int{1, 2, 3, 4}, func(n int) bool {
return n > 1
})
fmt.Println(xs) // [2 3 4]
}
package mainimport ("fmt")func main() {ii := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}s := sum(ii...)fmt.Println("all numbers", s)s2 := even(sum, ii...)fmt.Println("even numbers", s2)s3 := odd(sum, ii...)fmt.Println("odd numbers", s3)}func sum(xi ...int) int {total := 0for _, v := range xi {total += v}return total}func even(f func(xi ...int) int, vi ...int) int {var yi []intfor _, v := range vi {if v%2 == 0 {yi = append(yi, v)}}return f(yi...)}func odd(f func(xi ...int) int, vi ...int) int {var yi []intfor _, v := range vi {if v%2 != 0 {yi = append(yi, v)}}return f(yi...)}
Comments
Post a Comment