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?
An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.
Definition and Usage. The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With