News for hackers. Stuff that matters.
Re:Decoding JSON sum types in Go without panicking by josephg on Wednesday March 19, 2025 @08:06PM (#43418609)
Huh?

I really don't understand this perspective. Sum types are crazy useful for data modelling. A couple examples:

- Its quite common to need to model user input events. Eg, MouseClickEvent { mouseid, button }, KeyboardEvent { key, modifierFlags }, and so on. The most natural way to express this is using a sum type, and having an event loop which matches out the different event types.

- Actually, most events follow this pattern. Eg, window management events, event sourcing (in kafka), actor mailbox events, etc.

- I've been working in the field of collaborative editing for the last ~decade. There, we talk a lot about editing operations. For text editing, they're either Insert { position, content } or Delete { position, length }. Some systems have a Replace type too. Sum types are a much more natural way to express operations.

- Results are sum types. Eg, if I submit a request to an RPC server, I could get back Ok(result) or Err(error). Thats a sum type. Likewise, this is what I want when I call into the POSIX API. I don't want to check the return value. I want a function that gives me either a result or an error. (And not a result-or-null and error-or-null like you get in Go.)

How would you elegantly express this stuff without sum types? I guess for input events you could use a class hierarchy - but that makes it infinitely harder to implement data oriented design. Things like serialization / deserialization become a nightmare.

Frankly, all the alternatives to sum types seem worse. Now I've spent enough time in languages which have sum types (typescript, rust, swift, etc), I can't go back. I just feel like I'm doing the compiler's job by hand, badly.

Re:Decoding JSON sum types in Go without panicking by airstrike on Thursday March 20, 2025 @08:30PM (#43430633)
100% agreed. Unrelated but your blog is awesome.