66 points · by varankinv · 3y ago · 113 comments
The other 'gotcha' is that in switch statements the compiler can't tell whether you enumerated on all your cases as there is no true enum type so it's not uncommon to have a catch all default case that either returns an error or panics and hope you can catch it during tests if you missed a case.
I just wish go had proper sum types.
I believe it's in golangci-lint.
It's by far my favorite feature of Swift.
Enums + Payloads + switches are incredibly simple yet so effective. You can make a simple state object, isolate it with an actor, then stream it anywhere with Combine (or now Observability). You'll get full compiler safety too, forcing any new state to be handled everywhere.
You can even stack that with _generic_ payloads that conform to protocols, and if you're feel brave you can make those payloads equable completions for _typed returns_.
for example (I hate formatting on here, but I'll give it a shot)
// A user state enum that conforms to loggable.
// The state is generic, any object T that conforms to "Partner" protocol can be a partner
enum UserState<T: Partner>: Loggable {
// Your states
case loggedOut(error: String?)
case loggingIn(email: Email) // Email type is a string that's been validated
case loggedIn(authToken: String, user: User, partner: T)
case loggingOut(exampleBlock: (String) -> Bool) // You can embed a callback here
// Utility Functions
/// Is the user logged in?
func isLoggedIn() -> Bool {
switch self {
case .loggedOut, .loggingIn: return false
case .loggedIn: return true
}
}
/// Loggable conformance
func logText() -> String {
// switch that converts state into something that's safe for your logging service
}
}In the above, any subscriber that gets a UserState object can switch on it, and for example if you're logged in you 100% get the auth token, user, etc. It's impossible to be logged in without those in-context.
It might look something like this in your UI:
/// Called by a subscriber that's hooked in to the state stream
func onUserStateChanged(newState: UserState) {
switch newState {
case let .loggedOut:
// Impossible? Error UI
case let .loggingIn, .loggingOut:
// loading UI
case let .loggedIn(authToken: _, user: user, parner: partner):
// set some text "hello \(user.userName)"
// display an image: \(MyRemoteLoader.url(url: partner.primaryLogoURL))
// Button to website: Button(url: partner.homePageURL)
}
}add a new state later? The compiler will error in the 500 places in your codebase you didn't handle the new case with one build command.
What I really wish Go had was sum types, Rust style. That'd cover enumerations and more.
type Vehicle interface {
isVehicle()
}
type Car struct {}
func (c Car) isVehicle() {}
type Van struct {}
func (v Van) isVehicle() {}
func VehicleType(vehicle Vehicle) {
switch v := vehicle.(type) {
case Car:
fmt.Println("car")
case Van:
fmt.Println("van")
default:
fmt.Println("unknown vehicle")
}
This covers most, but not all, of the bases, in that you don't get exhaustiveness checking at compile time, unless you adjoin a linter to your compile process: https://github.com/BurntSushi/go-sumtypePattern matching and exhaustive checks are massive benefits of them though. I guess I'm just oddly conflicted here.
I do think that long term, sum types are going to become more prevalent. I'm excited to see it, I'm just interested in how that adoption occurs in existing languages without them.
Sum types are useful, even very useful in the right place, but I do think there's a lot of people who use them a couple of times, probably in one of those "right places" and then mistakenly label them in their mind as "better". Just, universally, Platonically "better". They aren't in fact "better"; they're a tool. Sometimes they're the right tool for the job, but much, much more often, they're just a tool that works, and so do several other tools. People who get too excited about sum types need to be sure they square their understanding of how useful they are with the fact that the vast majority of programs are written without them.
I feel this pain basically any time I hand-write lexical scanners/parsers in Go or even C++.
> I don't really care if you do or do not stay angry at the language you're forced to work in for your job. What I do want for you is to be able to make the best of the situation you're in and not be unhappy.
Because maybe enumerations in Go are subpar compared to other languages (FP or not).
This is especially true in cases where a function returns a collection of results where each result is independent from other results and a result can succeed or fail.
For instance, a batch report generator that is called every $INTERVAL might return a ([]Report metadata, error) today, but each report could have succeeded or failed without impacting the others.
The output is emailed to $SOMEONE to let them know the reports ran and information about each.
In today's world, the "error" could be a special error type that capture failures on a per report basis. The ReportMetadata type could also have an Error field, but one is not forced to check either.
Sum types could force checking for error on a per report basis, increasing the odds something is done with the error.
enum Message {
Action1(String, Option<Mode>),
Action2(String),
}
Action1 and Action2 are variants not types and I cannot make functions that take an Action1 or an Action2 as a parameter. To get around this people will often make each enum variant just a container for some struct with the same name but that's more verbose and matching becomes slightly uglier. Code like this is fairly common: struct Action1(String, Option<Mode>);
struct Action2(String);
enum Message {
Action1(Action1),
Action2(Action2),
}
Ideally I'd like to be able to succinctly say something like: type A = B | C
and have A be dependent on B and C but have both B and C be completely independent types.Is this... right? You can't use enum variants as types in function signatures, variable declarations, etc.
func main() {
c := color.Red
cptr := (*string)(&c)
*cptr = "orange"
PrintColor(c) // successfully compiles, and prints "orange"
}Casting is by definition an escape hatch.
c = Color("orange") does not compile.
package color
type Color interface {
void()
}
type color struct {
v string
}
func (c color) void() {}
func (c color) String() string {
return c.v
}
var (
Red color = color{"red"}
Green color = color{"green"}
Blue color = color{"blue"}
) func fn(c color.Color) {
switch c {
case color.Red, color.Green, color.Blue:
log.Printf("c=%#+v -- OK", c)
default:
log.Printf("c=%#+v -- should not be possible", c)
}
}
func main() {
var c color.Color
fn(c)
}
Output: c=<nil> -- should not be possible
:shrug: c := color.Red
c = Color("orange")
PrintColor(c)Doesn't matter, the point is they're getting in a value which is not part of the defined set, demonstrating that this emulation is not actually typed-safe.
> If that's the point you're intending to make, then couldn't you make it more easily with this?:
cannot convert "orange" (untyped string constant) to type Color"Oh but someone may try to cast arbitrary values to my package type" Okay but who is that going to hurt? You or them? Will they get hit with errors early on in the development lifecycle if they do something silly like this? Are you actually going through all these lengths for nothing?
It's not a bogeyman.
It's pkg.fun(someVar) where someVar is accidentally 0 or "" because it comes from 3 functions away.
Proper enums would be elegant, not this.
type Foo interface { A | B | C }
and the interface type is the union of those type-sets. Such interfaces can not currently be used outside of type constraints, but if that is relaxed, and type switches are updated to support and enforce exhaustive matching (and understand such sealed / nominative interfaces), you've got all the bits you need.You'd need to newtype variants to add payloads of similar underlying type e.g. `int | int`, but that's not a huge imposition, and the variants being types themselves is often convenient so it's a 50:50 tradeoff compared to classic sum type (where constructors disambiguate all variants but are not themselves types).
var foo interface{ A | B }
then foo either has to be boxed (so the default value is a nil interface) or unboxed and arbitrarily initialized as an A or a B.I don't see how unboxing would have to be "arbitrarily initialized as an A or a B" either. Even with a novel bespoke implementation you still need a discriminant between the two nested. You could keep a nil default by reserving the zero discriminant for that purpose.
var c color.Color
That's a valid color whether it's a nil interface value or an empty typed string.You can return a private type to prevent this, but that also means they can't refer to it as an argument or return value anywhere outside the implementing package, which is a rather severe limit in many cases.
Sometimes* I really miss constructors.
*: all the time
package color
type Color struct {
val string
}
func (c Color) String() string {
return c.val
}
var (
Red = Color{val: "red"}
Green = Color{val: "green"}
Blue = Color{val: "blue"}
)
Since `val` is not exported, external packages cannot create arbitrary `Color`.for enums I prefer just direct structs: https://github.com/nikolaydubina/go-enum-example
One idea is to make a DB table dedicated to enumerations and then use foreign key constraints. Define a unique namespace for each set of enumerated values, and catch foreign key constraint failures on DB writes.
But what problem does this actually solve?
When I see a type alias of a string and enumerated variants then why would I pass in arbitrary strings?
There are _always_ ways to break assumptions. Putting arbitrary, complex guard rails at every call site doesn’t make a program magically better.
An API is primarily about affordances. We provide utility to the caller.
Ideally, of course, the release notes of the library would spell out the issue, and you’d read them, but even then, making sure you fix this everywhere is way easier if the compiler refuses to compile your code if it doesn’t handle the new case.
This type of pattern can be used to force other developers to check if the value is garbage before calling $BUSINESS_LOGIC that uses the enum
type ColorWrapper struct {
color.Color
...
}
ColorWrapper will implement color.Color. I don't know what the point would be, but another way to break the compile-time type safety.As stated in that proposal, the interaction between what people want from “enums,” “discriminated unions,” “sum types,” (as well as “optional values” and “nil safety”) and fundamental Go tenets like zero values, make this a tough sell, which is very likely to make no one happy.
Unless you mean: is it enough of a language to be useful for its intended usages? In which case my decade of paychecks would like to let you know that it is, in fact, sufficiently complete for many business needs.
Enumerations aren't an advanced language feature at all and Go was released in 2010.