go - Why use a statement inside an "if" statement? -
the go tour shows illustration have statement in same line "if" statement , explain this: the if statement can start short statement execute before condition.
func pow(x, n, lim float64) float64 { if v := math.pow(x, n); v < lim { homecoming v } homecoming lim } i don't see need syntax , find confusing. why not write v := math.pow(x, n) in previous line?
the reason i'm asking i'm finding out, syntax finds way go language after careful consideration , nil seems there out of whim.
i guess actual question be: specific problem trying solve using syntax? gain using didn't have before?
there many utilize cases , not think feature tackles specific problem rather pragmatic solution problems encounter when code in go. basic intentions behind syntax are:
proper scoping: give variable scope needs have proper semantics: create clear variable belongs specific conditional part of codesome examples remember off top of head:
limited scopes:
if v := computestuff(); v == expectedresult { homecoming v } else { // v valid here } // carry on without bothering v error checking:
if perr, ok := err.(*os.patherror); ok { // handle path error } or more general, type checking:
if somestruct, ok := someinterface.(*somestruct); ok { // someinterface *somestruct. } key checking in maps:
if _, ok := mymap[somekey]; ok { // key exists } if-statement go
No comments:
Post a Comment