4 ms·
> Go compiler raise an error if a variable (error) goes unused It doesn't though. It's not a warning or error to not use the return value of a function that on
by HL33tibCe7 5y ago
> Go compiler raise an error if a variable (error) goes unused
It doesn't though. It's not a warning or error to not use the return value of a function that only returns an error, for instance (https://go.dev/play/p/se6-zHHVezH https://go.dev/play/p/se6-zHHVezH).
There are static error checking tools you can use like https://github.com/kisielk/errcheck https://github.com/kisielk/errcheck to work around this, but most people don't use them.
I've run into a lack of Go error checking many times. Many times it's just the trivial case, where the compiler doesn't warn about not checking the result of an error-returning function.
But often it'll be subtler, and the result of Go's API design. One example is its file writing API, which requires you to close the file and check its error to be correct. Many times people will just `defer file.Close()`, but that isn't good enough - you're ignoring the error there.
Worse still is e.g: writing to a file through a bufio.Writer. To be correct, you need to remember to flush the writer, check that error, then close the file and check that error. There's no type-level support to make sure you do that.
- jeroenhd 5y agoRust will allow you to ignore a Result as well, to be fair, though with a compile time warning. I don't think I know any language that'll throw a compiler error at you if you ignore the return value of a function that indicates success or failure.
- steveklabnik 5y agoLanguages with "linear types" would, but there aren't any mainstream ones. (And, to be extra clear, it only lets you ignore a Result if you don't care about the Ok value, if you want to use it, it does not.)
- masklinn 5y ago> It doesn't though. It's not a warning or error to not use the return value of a function that only returns an error, for instance (https://go.dev/play/p/se6-zHHVezH https://go.dev/play/p/se6-zHHVezH). An other issue which is as big or bigger is that Go only tracks variables, it doesn't track reads and writes (unlike... well rust for starters). So the compiler will also be perfectly happy if you call two erroring function, check the first's error but then reassign the second's error to the same variable (say, err, because it's always the variable for the error) and... completely forget to check it: https://go.dev/play/p/GJiovZwvHqj https://go.dev/play/p/GJiovZwvHqj I think errcheck also checks for it, but as you say it's not part of the language and its use is not ubiquitous.