Skip to content

Commit 1f1fe2f

Browse files
committed
add closures eg
1 parent ec9020c commit 1f1fe2f

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

codes/ch2_functions/closures.go

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package main
2+
3+
import "fmt"
4+
5+
/**
6+
* User defined type Profile act as struct type
7+
*/
8+
type Profile struct {
9+
name string
10+
username string
11+
message string
12+
}
13+
14+
type Printer func(string) ()
15+
/**
16+
* Define a CreateMessage function;
17+
*
18+
* username is variadic function, can only use ... as final argument in list
19+
*/
20+
func CreateMessage(name string, username string, message ...string) (welcome string, info string) {
21+
22+
/**
23+
* <naming-return-val1> = string
24+
* <naming-return-val2> = string
25+
*/
26+
welcome = "\n" + message[0] + " " + name
27+
info = "You are authorize to access the system: " + username + "\n"
28+
29+
fmt.Println(message[1])
30+
fmt.Println(message[2])
31+
fmt.Println("Number of parameters: ", len(message))
32+
33+
return
34+
}
35+
36+
func Print(s string) {
37+
fmt.Print(s)
38+
}
39+
40+
func PrintLine(s string) {
41+
fmt.Println(s)
42+
}
43+
44+
func CreatePrintFunction(custom string) Printer {
45+
return func(s string) {
46+
fmt.Println(s + custom)
47+
}
48+
}
49+
50+
51+
/**
52+
* Define a Greeting function;
53+
*/
54+
func Greeting(github Profile, do Printer) {
55+
56+
wel, inf := CreateMessage(github.name, github.username, github.message, "Go is concurrent", "Go is awesome")
57+
58+
/**
59+
* Commenting exact below "Println(wel) line would throw an error "wel declared and not used"
60+
* In case you want to ignore the wel declaration and use info => replace wel with _ as below syntax
61+
*
62+
* E.g. _, info := CreateMessage(github.name, github.username, github.message)
63+
*/
64+
do(wel)
65+
do(inf)
66+
67+
// fmt.Println(_) // Cannot use _ as value
68+
}
69+
70+
func main() {
71+
72+
var github = Profile{"Ashwin Hegde", "hegdeashwin", "Welcome to Go world!"}
73+
74+
/**
75+
* Call the function and pass the data to the function
76+
*/
77+
Greeting(github, CreatePrintFunction("?"))
78+
}

0 commit comments

Comments
 (0)