Is A same as B?
A
if err := json.NewDecoder(r.Body).Decode(&t); err != nil {
rnd.JSON(w, http.StatusProcessing, err)
return
}
B
err := json.NewDecoder(r.Body).Decode(&t);
if err != nil {
rnd.JSON(w, http.StatusProcessing, err)
return
}
CodePudding user response:
They are equivalent except one difference: the scope of the err
variable. In the A version the scope of the err
variable is the if
statement: it's not accessible after the if
.
In the B version the err
variable will be in scope after the if
statement too, and if err
is already defined earlier, it could result in a compile-time error too.
It's good practice to always minimize the scope of variables (which gives you less chance to misuse them). If you do not wish to further examine the returned error after the if
, it's better to use the A version. If you do need it after the if
, then obviously the B version is the way to go.