I am attempting to create a sort of function that is similar to the Express (NodeJS) route method in Go:
app.get("route/here/", func(req, res){
res.DoStuff()
});
In this example I want "foo" (the type) to be the same as the anonymous function in the above method. Here is one of my failed attempts using Go:
type foo func(string, string)
func bar(route string, io foo) {
log.Printf("I am inside of bar")
// run io, maybe io() or io(param, param)?
}
func main() {
bar("Hello", func(arg1, arg2) {
return arg + arg2
})
}
How might I fix my dilemma? Should I not use a type and use something else? What are my options?
You are on the right track - creating a type for a func on the context you are using it adds clearer design intent and more importantly additional type safety.
You just need to modify you example a bit for it to compile:
package main
import "log"
//the return type of the func is part of its overall type definition - specify string as it's return type to comply with example you have above
type foo func(string, string) string
func bar(route string, io foo) {
log.Printf("I am inside of bar")
response := io("param", "param")
log.Println(response)
}
func main() {
bar("Hello", func(arg1, arg2 string) string {
return arg1 + arg2
})
}
package main
import (
"fmt"
"log"
)
type foo func(string, string)
func bar(route string, callback foo) bool {
//...logic
/* you can return the callback to use the
parameters and also in the same way you
could verify the bar function
*/
callback("param", "param")
return true
}
func main() {
fmt.Println("Hello, playground")
res := bar("Hello", func(arg1, arg2 string) {
log.Println(arg1 + "_1")
log.Println(arg2 + "_2")
})
fmt.Println("bar func res: ", res)
}