Re:A rough proposal for sum types in Go (2018)
by kadoban on Tuesday November 16, 2021 @06:53PM
(#29247793)
How does go's type system allow the "exactly one of these two" case? What's the syntax?
Re:A rough proposal for sum types in Go (2018)
by BobbyJo on Thursday November 18, 2021 @10:20PM
(#29273421)
I'm not sure what you're asking. I was pointing out that if you need to enforce a return result that will have either a value or an error, you can simple write a struct/interface that does that.
Like, you can create an interface that's read only for the return result like:
interface ReadableResult { HasResult() bool Result() whatever Error() error }
Then to create the result you have a writable interface for setting values, and enforce the 'only one of the two' semantics from the setters:
interface WritableResult { SetResult(whatever) SetError(error) }
Struct MyResult{ err error result whatever }
.... Implementation here.
It's extra code, but it should be a rare necessity, at least in my experience. Res, err := getResult() always worked fine for me.
Go's type system can already do that, the (x, error) idiom is just standard practice in the absence of Generics and Throwables. Adding generics simply flips the default and exception.
Currently, the exception is to define a custom type which captures and constrains your possible return states, and the default is to return a value plus an error. When that flips, and the default is to collapse error states into a single return value, that will cease to give me the same signals (or at least make them less obvious) as to whether or not my abstraction sucks, which I will sorely miss :P