The Go tour shows an example where they have an extra statement in the same line as the "if" statement and they explain it like this: the if statement can start with a short statement to execute before the condition.
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
I don't see the need for this syntax and find it very confusing. Why not just write v := math.Pow(x, n)
in the previous line?
The reason I'm asking is that for what I'm finding out, syntax finds its way into the Go language after careful consideration and nothing seems to be there out of whim.
I guess my actual question would be: What specific problem are they trying to solve by using this syntax? What do you gain by using it that you didn't have before?
There are many use cases and I do not think this feature tackles a specific problem but is rather a pragmatic solution for some problems you encounter when you code in Go. The basic intentions behind the syntax are:
Some examples that I remember off the top of my head:
Limited scopes:
if v := computeStuff(); v == expectedResult {
return v
} else {
// v is valid here as well
}
// carry on without bothering about v
Error checking:
if perr, ok := err.(*os.PathError); ok {
// handle path error specifically
}
or more general, Type checking:
if someStruct, ok := someInterface.(*SomeStruct); ok {
// someInterface is actually a *SomeStruct.
}
Key checking in maps:
if _, ok := myMap[someKey]; ok {
// key exists
}
Because so your variables are contained in the scope Notice that those v
are declared on different scope.
A more direct example to understand scopes: http://play.golang.org/p/fInnIkG5EH
package main
import (
"fmt"
)
func main() {
var hello = "Hello"
{
hello := "This is another one"
fmt.Println(hello)
}
if hello := "New Hello"; hello != ""{
fmt.Println(hello)
}
fmt.Println(hello)
}