Skip to content

Commit 6f69415

Browse files
committed
add passing-a-function eg
1 parent a63d31e commit 6f69415

File tree

1 file changed

+71
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)