Ok. I have some trouble understanding what exactly is going on here with "MyPrinter" Let me go step by step (please correct me if got something wrong)
1. The "Salute" structure is created
2. Call to "Greet" function
2.a Call to "CreatePrinterFunction" with the strgin "!!!". This function returns a "MyPrinter" (witch is a function that takes in a string and returns nothing)
3. the variables "message" and "defaultMessage" are set with the strings
Now here's the problem, I don't understand what exactly are those do("str") doing
package main
import "fmt"
type Salute struct {
name string
greeting string
}
type MyPrinter func (s string) ()
func Greet(salute Salute, do MyPrinter) {
message, defaultMessage := CreateMessage(salute.name, salute.greeting, "noName")
do(message)
do(defaultMessage)
}
func Print(s string) {
fmt.Print(s)
}
func PrintLine(s string) {
fmt.Println(s)
}
func CreatePrinterFunction(custom string) MyPrinter {
return func (s string) {
fmt.Println(s + custom)
}
}
func CreateMessage(name string, greeting ...string) (message string, defaultMessage string) {
message = name + " " + greeting[0]
defaultMessage = "hey " + name
return
}
func main() {
var s = Salute{"Joe", "hello"}
// Greet(s, PrintLine)
Greet(s, CreatePrinterFunction("!!!"))
}
CreatePrinterFunction
returns a function literal:
return func (s string) {
fmt.Println(s + custom)
}
That function literal implements the MyPrinter interface, which is an interface implemented by any function that takes a string argument and returns nothing:
type MyPrinter func(s string)
(note that the MyPrinter
definition in the provided snippet includes an extra ()
at the end which does nothing)
Then, that function created which implements the MyPrinter interface is passed as the do
parameter of the Greet
function:
func Greet(salute Salute, do MyPrinter) {
When code inside Greet
runs do(message)
, the created function literal is called, which in its turn runs the equivalent of fmt.Println(message + custom)
.
It's a pretty convoluted way to do something simple. :-)