Error checking is a complicated problem. It is like a garbage problem; everyone produces garbage, but no one wants to pick it up. Errors come from code that might behave unexpectedly due to forces outside of the developer’s control. Code accepts user input, and it will do its best to make sense of it, but there are scenarios where it is not possible for the code to handle the data that it was given (the code does addition but gets “hamburger”). Maybe the file that was expected to be at some location isn’t, what then? A naive approach to handling this is ceasing the execution of the program, the equivalent of putting your hands up and saying, “fuck this shit, I’m done here”. If your code is simple and only being used by you, this might be OK, but what happens when other people want to use your code? To the code caller, the panics will be set off like hidden land mines to them.

In Go, errors are treated as values rather than being thrown and caught like in other languages. This approach has several advantages:

  • Explicit error handling: In Go, errors are returned as values and need to be handled explicitly by the caller. This forces developers to think about and address potential errors at the point where they occur rather than burying them in a try-catch block or ignoring them altogether. This helps in writing more robust and reliable code.

  • Error propagation: In Go, errors are passed up the call stack as regular values would be, allowing for easy propagation of errors through function calls. This makes it easier to track where errors originate and how they are handled throughout the program.

  • Clean and simple error handling: By treating errors as values, Go code tends to have clean and simple error handling mechanisms. Developers can easily check for errors using if statements and handle them in a way that makes sense for their specific use case.

  • Less overhead: Because errors are not thrown and caught, there is less overhead involved in error handling in Go compared to languages that use exceptions. This can lead to better performance in error-prone code paths.

Overall, treating errors as values in Go results in more explicit and concise error handling, making it easier to write reliable and maintainable code.