|
|
|
|
|
by ebingdom
1839 days ago
|
|
Because the typical situation with error handling is that there are two possible cases: (a) a function succeeds with some result, or (b) it fails with an error. A sum type represents those two possibilities exactly. In contrast, a product type says "I have both a result and an error", which makes no sense. However, if things can be nil, which is the norm in Go, then you can represent both (a) and (b) with a product type, but you also have two additional cases to worry about: (c) both the result and the error are present, and (d) both are nil (and what are you supposed to do in that situation?). When using static types, it is best to make as few nonsensical/illegal/invalid states representable as possible, so that you can rely on the compiler enforcing that they won't happen. Functional programmers have been saying this for decades, and these days Rust programmers are generally onboard with this too. Sum types are the categorical dual of product types, so it always seems unnatural to me when a language only has the latter and not the former. I think part of the problem is we don't teach category theory to programmers, so they never stop to consider the duals of things. |
|