DEV Community

Sukma Rizki
Sukma Rizki

Posted on

Implementation of function as Parameters

The way to create a function as a function parameter is direcly write the function schema as a data type, let s look example below

package main
import "fmt"
import "strings"

func filter(data []string, callback func(string) bool) []string {
 var result []string
 for _, each := range data {
 if filtered := callback(each); filtered {
 result = append(result, each)
 }
 }
 return result
}


Enter fullscreen mode Exit fullscreen mode

The callback parameter is a closure declared of type
func(string) bool . The closure is called in each loop in the function
filter() .
We created the filter() function itself for filtering array data (the data obtained
from the first parameter), with filter conditions that can be determined by yourself. Under
This is an example of utilizing this function

func main() {
 var data = []string{"wick", "jason", "ethan"}
 var dataContainsO = filter(data, func(each string) bool {
 return strings.Contains(each, "o")
 })
 var dataLenght5 = filter(data, func(each string) bool {
 return len(each) == 5
 })
 fmt.Println("data asli \t\t:", data)
 // data asli : [wick jason ethan]
 fmt.Println("filter ada huruf \"o\"\t:", dataContainsO)
 // filter ada huruf "o" : [jason]
 fmt.Println("filter jumlah huruf \"5\"\t:", dataLenght5)
 // filter jumlah huruf "5" : [jason ethan]
}
Enter fullscreen mode Exit fullscreen mode

There's quite a lot going on in each call to the filter() function
on. The following is the explanation.

  1. The array data (obtained from the first parameter) will be looped.
  2. In each iteration, the closure callback is called, with data inserted each loop element as a parameter.
  3. The closure callback contains a filtering condition, with a result of type bool which is then used as a return value.
  4. In the filter() function itself, there is a condition selection process (which value obtained from the results of executing the closure callback). When the condition is worth it true , then the data element that is being repeated is declared to have passed the process filtering.
  5. The data that passes is accommodated in the result variable. These variables are made as the return value of the filter() function.

Top comments (0)