map controlCenters = database.getControlCenters(); // returns map column->value, nil if no connection
int controlCentersInExistence = controlCenters["count"]; //FIXME - use the other syntax, I forgot how it looked like
if (controlCentersInExistence == 0) { // someone nuked USA!
WW3Manager.launchMissiles(); // we need to retaliate!
} controlCenters, err := database.getControlCenters()
if err != nil {
return fmt.Errorf("couldn't get map of control centers: %v", err)
}
// now we know controlCenters is valid.
controlCentersInExistence, ok := controlCenters["count"]
if !ok {
return errors.New("no count of control centers!")
}
// now we know the column existed
if controlCentersInExistence == 0 {
WW3Manager.launchMissiles()
}
Go's conventions are actually excellent at making this code MUCH more robust.BTW err != nil? I don't know, it seem fragile. Maybe it's years of exception indoctrination speaking, but I am scared that someone will return false for errors and someone else will check err != nil, or the reverse, or some other misunderstanding, and it will fail.
I'm confused. Previously you gave this example:
a, ok := m[1] // returns 0, false
Which means that `ok == false`. But how can it be false if that is not a valid value for an error?About your original point about someone returning "the wrong thing" in an error... there's really no misunderstanding possible. Because Go is statically typed, the ONLY things you can return for an error are nil (no error), or something that fulfills the error interface (a type with a method Error() that returns a string). You can't return false, or 0, or "" when the code expects you to return an error... the compiler won't let you.
This is how all error handling works in Go. From the most basic program you write, you learn that err == nil means success, anything else means failure.
Does that help any?