Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The section on "enums and pattern matching" in the Rust book is probably a good place to start: https://doc.rust-lang.org/book/ch06-00-enums.html

A "Rust enum" is a sum type.

Also, I talked about ASTs being a good example use case for a sum type. Here's a "real" version of an AST for a regular expression in all its complex glory: https://github.com/rust-lang/regex/blob/a9b2e02352db92ce1f6e...

You can see that it starts out as a sum type at the top level. And inside each variant is all sorts of product types and other sum types.

But do note in practice that sum types aren't limited to specialized things like ASTs. In practice, they come up everywhere. For example, here's a small little state machine used to implement a simple "unescape" routine. e.g., converting the string 'a\xFF\t' to the byte sequence 0x61 0xFF 0x09: https://github.com/BurntSushi/ripgrep/blob/44fb9fce2c1ee1a86...



Are there other examples of sum types besides enums, in Rust? Are the two terms synonymous?


Rust does not have sum types outside of enums. Other languages have sum types, and may or may not call them enums depending on the language.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: