Take a look at this page in Tour of Go. It explains that:
Like for, the if statement can start with a short statement to execute before the condition.
Given your example:
h, ok := route[request.URL.String()]; ok { ... }
The short statement is h, ok := route[request.URL.String()]. The ; after marks the end of the short statement. The ok that follows is the condition. If true, then the code block {...} is executed. In that code block you can use all the variables that were assigned in the short statement.
first off, how can it be valid syntactically to declare ok after it is assigned to the result of route()?
ok is not declared after it is assigned. It is a boolean value, used in the condition.
second, if h is returned byroute(), how can it be used in the definition ofok`???
It's not definition of ok. It's the code block of the if statement.
Consider this alternative, almost equivalent writing style:
h, ok := route[request.URL.String()]
if ok {
h(writer, request)
return
}
This is perfectly clear, right? We just split the original code to two steps. But this is not the same. When writing this way, the h and ok variables are visible after the if statement. This is not desirable. It's a good practice to minimize the visibility of variables (also known as the live time). The longer a variable is visible, the longer the window of vulnerability during which it can be accidentally misused. This syntax of Go is truly great, genius, and I don't know a single other language where this kind of if statement is possible.
See also the section on the if statement in Effective Go.
okis not an assignment but the expression of theifstatement.