dev-resources.site
for different kinds of informations.
Implementation of function as Parameters
Published at
4/26/2024
Categories
backend
go
godev
basic
Author
Sukma Rizki
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
}
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]
}
There's quite a lot going on in each call to the filter() function
on. The following is the explanation.
- The array data (obtained from the first parameter) will be looped.
- In each iteration, the closure callback is called, with data inserted each loop element as a parameter.
- The closure callback contains a filtering condition, with a result of type bool which is then used as a return value.
- 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.
- The data that passes is accommodated in the result variable. These variables are made as the return value of the filter() function.
Articles
12 articles in total
Flutter Design Pattern Bussines Logic Component (BLOC)
read article
Design Pattern in Flutter MVVM
read article
Interesting Control Flow in the circle
read article
Query a database Using Go
read article
Level Basic Junior Programming Go
read article
Unit Test At Go
read article
Reading data from Mysql server
read article
Web Service Api Server in Go
read article
Pipeline Concept
read article
Concurrency Pattern Pipeline
read article
How to Use Http Request
read article
Implementation of function as Parameters
currently reading
Featured ones: