-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanonymous-function.go
More file actions
58 lines (48 loc) · 1.11 KB
/
anonymous-function.go
File metadata and controls
58 lines (48 loc) · 1.11 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import "fmt"
type Blacklist func(string) bool
// function with parameter of function type
func registerUser(name string, isBlacklist Blacklist) {
if isBlacklist(name) {
fmt.Println("You are blocked")
} else {
fmt.Println("Welcome", name)
}
}
// normal function
func isBlacklisted(name string) bool {
blacklistUser := []string{"admin", "root", "sys"}
for _, user := range blacklistUser {
if user == name {
return true
}
}
return false
}
func main() {
// anonymous function
// for simple way to write function
// regular function
registerUser("admin", isBlacklisted)
// anonymous function #1 (for simple way)
registerUser("guest", func(user string) bool {
blacklistedUser := []string{"admin", "root", "sys"}
for _, name := range blacklistedUser {
if user == name {
return true
}
}
return false
})
// anonymous function #2 other style
blacklisted := func(user string) bool {
blacklistedUser := []string{"admin", "root", "sys"}
for _, name := range blacklistedUser {
if user == name {
return true
}
}
return false
}
registerUser("root", blacklisted)
}