Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a statement inside an "if" statement?

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?

like image 544
Julian Avatar asked Jun 19 '14 23:06

Julian


People also ask

Is it necessary to have an ELSE clause in an IF statement?

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.

Why do we use if-else statements?

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.


1 Answers

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:

  • proper scoping: Give a variable only the scope that it needs to have
  • proper semantics: Make it clear that a variable only belongs to a specific conditional part of the code

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
}
like image 180
nemo Avatar answered Nov 15 '22 09:11

nemo