func main() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r http.Request) {
// I never declared, initialized or passed w and r. How does this function get access to them?
}
2 Answers
http.HandleFunc knows its given input parms and that 2nd parm will have its own input parms (w http.ResponseWriter, r http.Request) ... so w and r are setup by http.HandleFunc which after it registers func handler as a callback it then invokes passing in w and r ... so responsibility is given to calling context not inside the callback definition itself
Its a worth while exercise to write your own such pair of functions where one is a callback passed into and invoked by other function ... this pattern is orthogonal to golang and is a pervasive tool across languages