|
|
|
|
|
by zaphar
5017 days ago
|
|
I respectfully disagree. You almost never cast the error. Two approaches are common in the go community. 1. Error constants. These you can use == or a switch statement to do control flow with. 2. Custom Error Types. These you typically use a type switch which uses reflection to do dispatch off. In this case you might also then cast it if you need specific data off of the error but most of the time you don't need any more than the string the error() method returns. Both of these cases use errors in the way go intends them to be used. For control flow at the location where it makes the most sense. |
|
edit:
You should note that the above test code is actually far less verbose than the analogous end-user code, given that the timeout_test.go clearly expects the 'err' var to be a net.Error.
Now consider the case of a network subsystem, with funcs having in args of type 'bufio.Reader' and/or 'bufio.Writer'. At some prior point you may have set 'net.Conn.SetReadDeadline(aPointInTime)', and in your stream processing funcs you may naturally encounter either net.Error (due to timeout) or buffer overruns, etc.
What would call site look like? Can you safely cast to (net.Error) like the test code? Not unless you can live with panics on interface type mismatch.