by randomdata · 2y ago · 0 comments
No doubt because the Go team disagrees. They have been abundantly clear that, from their point of view, goroutines should be used and even used as part of the public API when it makes sense.
That said, it is still probably really good advice for newcomers who won't have a good understanding for the cases where it does make sense, and especially because goroutines are the shiny thing every newcomer wants to play with and will try to find uses that don't make sense just to use it. As a rule, you don't want to force the caller into things they might not want. In the vast majority of cases, a synchronous API is what you will want to give them as it is the most versatile.
And, really, that's something that applies generally. For example, in the case of the common (T, error) pattern, you will want to ensure T is always useful even when there is an error. The caller may not care about the error condition. That's not you for, the library author, to decide. The fewer assumptions you can make about the caller the better.
This applies to maybe 0.1% of functions. The overwhelming majority of functions, in the Go stdlib as well as real projects, that return (T, error) return an empty meaningless value for the error cases.
In practice, that typically means returning the zero value. To which idioms suggest that zero values should be useful. Rob Pike's Go Proverb[1] even states: "Make the zero value useful." Most commonly when returning (T, error) that zero value is nil. In Go, nil is a useful value!
If the caller wants to observe the error state, great. But it is needlessly limiting if you force it upon them. That is not for the library author to decide.
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".)
There is nothing special about errors.
There are some rare cases where a 0 value is actually meaningful in some way. But even for types where it is fully functional like integers, it's often not meaningful in the specific context it is used.
> Not my experience.
To what experience do you speak of? My 5,000+ hours in kubernetes and terraform space tells me Rob Pike's views are fan fiction at best.
What new code being written today is violating that pattern?