2 ms·
One problem I've found as a newcomer to Go (and I'm perfectly willing to accept that I just haven't developed the right "language mindset" yet) is that the zero
by deergomoo 3y ago
One problem I've found as a newcomer to Go (and I'm perfectly willing to accept that I just haven't developed the right "language mindset" yet) is that the zero value can be problematic—particularly for scalar types—because it's often a perfectly valid value in a model where you need a way to indicate an invalid value.
Obviously if there is a possibility of invalidity, you would expect the caller to check the error, but the fact that I always have to return something as the callee, and always have to make sure I'm not accidentally using the value in error conditions as the caller, is just asking for mistakes to me.
I appreciate that it's not the path Go has chosen to tread, but I find Result<T, Error> to be so much more of a foolproof pattern than (T, error), especially considering prevention-of-foot-shooting is an established Go design goal.
(Equally obviously you could use a pointer and return nil, but I find that muddles the semantics, because there are multiple reasons you might opt to use pointers besides the ability to express "no value".)
- Kamq 3y agoIf the zero value is valid, I usually just use a pointer to the scalar type in question
- randomdata 3y agoGiven (T, error), what do you return for error when no error occurred? When error is "invalid"? The caller is, no doubt, expecting you to be consistent, so the answer for T no doubt lies therein. There is nothing special about errors.