-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction-as-parameter.go
More file actions
41 lines (32 loc) · 944 Bytes
/
function-as-parameter.go
File metadata and controls
41 lines (32 loc) · 944 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import "fmt"
// we can put like this in here
func greetMorning(name string, filter func(string) string) string {
return "Good Morning " + filter(name)
}
// or we can put type definition as a alias and put in parameter
type Filter func(string) string
func greetMorningAlias(name string, filter Filter) string {
return "Good Morning " + filter(name)
}
// notice that the function must have same signature in parameter above
func filter(name string) string {
if name == "kotor" {
return "****"
} else {
return name
}
}
func main() {
// function as parameter
// we can pass functions as parameters to other functions
result := greetMorning("kasar", filter)
fmt.Println(result)
result = greetMorning("Luthfi", filter)
fmt.Println(result)
// with type declaration as alias
result2 := greetMorningAlias("kotor", filter)
fmt.Println(result2)
result2 = greetMorningAlias("Akbar", filter)
fmt.Println(result2)
}