Comment

Comment by articulatepang

Yes, the type I wrote down is isomorphic to Option<int32>, so the compiler will ultimately generate the same machine code and do the same optimizations.

But defining a new type allows you to give the two cases more descriptive names. That saves you from having to remember and comment what the two cases represent. In a small but significant way, the code documents itself.

Also, doing it this way gives the Connection type its own name and identity separate from Option<int32>. So if you have a function that takes a Connection and some other Option<int32>, you can’t accidentally switch them: even though the two types are equivalent for optimizations and codegen, they’re NOT equivalent for the type checker.

It also makes function signatures more self-documenting: you can tell just from the type that the function takes or returns a Connection, and that helps in a small but real way to understand what it does.

I like programming like this a lot! So much so that the reason I personally like Rust a lot is simply that it’s a mainstream language with great tooling that has sum types and reasonable generics. It’s like if OCaml or Haskell had the community or tooling, or if Go or Python had the type features.

No comments yet

Be the first to share your thoughts.

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton