Does Go allow a function to use another function as a parameter?

The problem occurs on line 17 in the Go code. The following is a program in python and Go so you can see exactly what I'm trying to do. Python works, my Go attempts all failed. Already read golang.org, and google also showed nothing.

def my_filter(x):
  if x % 5 == 0:
    return True
  return False

#Function which returns a list of those numbers which satisfy the filter
def my_finc(Z, my_filter):

  a = []
  for x in Z:
    if my_filter(x) == True:
      a.append(x)
  return a

print(my_finc([10, 4, 5, 17, 25, 57, 335], my_filter))

Now the Go version I'm having problems with:

package main

import "fmt"

func Filter(a []int) bool {
    var z bool
    for i := 0; i < len(a); i++ {
        if a[i]%5 == 0 {
            z = true
        } else {
            z = false
        }
    }
    return z
}

func finc(b []int, Filter) []int {
    var c []int
    for i := 0; i < len(c); i++ {
        if Filter(b) == true {
            c = append(c, b[i])
        }
    }
    return c
}

func main() {
    fmt.Println(finc([]int{1, 10, 2, 5, 36, 25, 123}, Filter))
}
+4
source share
1 answer

Yes, Go can have functions as parameters:

package main

import "fmt"

func myFilter(a int) bool {
    return a%5 == 0
}

type Filter func(int) bool

func finc(b []int, filter Filter) []int {
    var c []int
    for _, i := range b {
        if filter(i) {
            c = append(c, i)
        }
    }
    return c
}

func main() {
    fmt.Println(finc([]int{1, 10, 2, 5, 36, 25, 123}, myFilter))
}

The key is you need the type to be passed.

type Filter func(int) bool

I also cleared some code to make it more idiomatic. I replaced your cycles with range suggestions.

for i := 0; i < len(b); i++ {
    if filter(b[i]) == true {
        c = append(c, b[i])
    }
}

becomes

for _, i := range b {
    if filter(i) {
        c = append(c, i)
    }
}
+8
source

Source: https://habr.com/ru/post/1525547/


All Articles