Sheshank Kodam
Sheshank Kodam

Reputation: 515

How to return from function types when using closures in Go

Im new to GoLang and cannot figure out whats wrong in the code below. What i'm trying to do is "Create and return Printer function on the fly"

type Salutation struct {  name string   
    greeting string
}

type Printer func(s string) string

func Greet2(salutation Salutation, do func(string)) (string){
    do(salutation.name + " " + salutation.greeting)
    return "Done"
}

func createPrintFunction(custom string) Printer {
    return func(s string) string {
        return "hello"
    }
}

func pluralSightModule1Closures1(w http.ResponseWriter, r *http.Request) {
    var s = Salutation{"Joe", "Hello"}
    res := Greet2(s, createPrintFunction("!!!"))
    w.Header().Set("Content-Type", "application/json")
    w.Write([]byte (res))
}

I get the following compilation error

 cannot use createPrintFunction("!!!") (type Printer) as type func(string) in argument to Greet2

Upvotes: 1

Views: 112

Answers (2)

Sheshank Kodam
Sheshank Kodam

Reputation: 515

Solution:

func Greet2(salutation Salutation, do Printer) (string){
    return do(salutation.name + " " + salutation.greeting)
}

type Printer func(string) string

func createPrintFunction(custom string) Printer {
    return func(s string) string {
        return s
    }
}

func pluralSightModule1Closures1(w http.ResponseWriter, r *http.Request) {
    var s = Salutation{"Joe", "Hello"}
    res := Greet2(s, createPrintFunction("!!!"))
    w.Header().Set("Content-Type", "application/json")
    w.Write([]byte (res))

}

Upvotes: -1

Schwern
Schwern

Reputation: 164679

The problem is the signatures don't match. That includes the return type.

Greet2 wants func(string) but createPrintFunction returns func(s string) string. Note that Greet2's returns nothing, but the createPrintFunction function returns a string.

You'll have to decide how to make them match. You probably want to use the return value in Greet2 for something better than "Done".

func Greet2(salutation Salutation, do func(string) string) string {
    return do(salutation.name + " " + salutation.greeting)
}

Since you've defined type Printer func(s string) string its best to use it consistently to avoid this sort of problem. Greet2 takes a Printer and createPrintFunction returns a Printer. Then if Printer changes things will still work.

func Greet2(salutation Salutation, do Printer) string {
    return do(salutation.name + " " + salutation.greeting)
}

...but the do generated by createPrintFunction doesn't use its arguments. It's hard to advise what it should do because much of this code just passes its arguments straight through, or ignores them.

Anyhow, the signatures have to match.

Upvotes: 3

Related Questions