On GO's unused variable error
Many people have ranted about the GO compiler’s insistance on all variables being used.
On a surprisingly related note, I wondered what’s forcing me to deal with errors if they’re just a separate value.
It’s not too difficult to find opinion upon opinion on this subject.
I also used to think this was kind of annoying however after gaining some knowledge on linear types, and other forms of dealing with errors and program flow I realized that there is one great reason to keep this.
Imagine now that you want to open a file in Go:
f := os.Open("...")
Okay, now the compiler states
assignment mismatch: 1 variable but os.Open returns 2 values
Right, opening can fail, lemme just…
f, err := os.Open("...")
declared and not used: err
You see?
This forces me to deal with the error in some way.
I could obviously have just added f, _ but that
would’ve been a visible smell.
Programmers are forgetful, distracted and time-pressured human beings so having anything remind you that something needs to be done that isn’t visible is a boon.
I think that considering their goal is “simplicity” just forcing every variable to be used is a reasonable solution to the “what if someone forgets to handle my error value” issue. Implementing this in other ways is probably more “complex” and unused variables are something people expect to be a warning anyway.
Ignoring all the returns is not a warning, which is okay here as you always want to hold on to the result, however something that returns an error but otherwise either side-effects or works on arguments might go uncaught.
I do have one more point though on the os.Open API,
forgetting to defer closing of the file is unchecked afaik,
however that is handled already
by the .Open function and defer just makes closing more predictable
as opposed to relying on GC. So that’s alright.