5 ms·
> Would be really cool if there was a code snippet in Rust comparing/explaining the advantage over Java for each benefit. Yeah, I thought about that. But the p
by Expurple 2y ago
> Would be really cool if there was a code snippet in Rust comparing/explaining the advantage over Java for each benefit.
Yeah, I thought about that. But the post kept and kept expanding in scope so I decided to instead hyperlink where I could.
> It's also not clear to me how `if let , while let , let-else` help (and how you'd use them)
All three of those are hyperlinks in the post.
> what an "ergonomic sum type" is
Here, I mean language support for defining and using sum types[1] without verbose code that doesn't reflect the programmer's intent well.
A typical sum type implementation in Java uses a sealed interface. You can't implement interfaces on "foreign" types that you don't control, like `boolean`. You often have to define extra wrapper classes that distract you when navigating the codebase and also hurt performance:
public sealed interface MutuallyExclusiveFlags permits FlagA, FlagB {}
public record FlagA(boolean value) implements MutuallyExclusiveFlags {}
public record FlagB(boolean value) implements MutuallyExclusiveFlags {}
Meanwhile, in Rust:
pub enum MutuallyExclusiveFlags {
FlagA(bool),
FlagB(bool),
}
No boilerplate, no extra types, no unnecessary performance cost. This whole object takes only 2 bytes of memory on the stack! [2]
I didn't go into detail on this, because the post isn't about introducing sum types.
> and how it helps with exceptions
The part about "exceptional flow" describes some cases where Result-based error handling is preferable to using exceptions. Language support for sum types is necessary to properly express Result values and the sets of possible error values inside.
[1] https://en.wikipedia.org/wiki/Tagged_union https://en.wikipedia.org/wiki/Tagged_union
[2] https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=316ac4f5922988cffffeceb5c60fe59a https://play.rust-lang.org/?version=stable&mode=debug&editio...