4 ms·
The fix is pretty simple, just declare err ahead of time: func doThing() string { result := "OK" var err error if result, err =
by assbuttbuttass 5y ago
The fix is pretty simple, just declare err ahead of time:
func doThing() string {
result := "OK"
var err error
if result, err = somethingelse(); err != nil {
return "ERROR"
}
return result
}
- rocqua 5y agoPart of the reason OP liked the `if assignment` was to avoid polluting the higher-level scope with a variable that is only needed during the if statement. Your solution fixes the error, but at the cost of losing the upside OP saw.
- jaggederest 5y agoIs there no equivalent to a lexical scope let definition? let { var err := error scoped code }
- usrbinbash 5y agoOf course there is: { var err error scoped code }
- ptomato 5y agoyes, you can wrap code in {} to scope it.
- Gwypaas 5y agoThe issue is now you have a potential nil value hanging around in the code with no real reason for its existence. Three refactors and some moving around later and you manage to hit a runtime panic in production.