3 ms·
Can someone elaborate on what sum types are and an example in Rust?
by endorphine 4y ago
Can someone elaborate on what sum types are and an example in Rust?
- burntsushi 4y agoThe 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 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/a9b2e02352db92ce1f6e5b7ecd41b8bbffbe161a/regex-syntax/src/ast/mod.rs#L469 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/44fb9fce2c1ee1a86c450702ea3ca2952bf6c5a7/crates/cli/src/escape.rs#L6-L17 https://github.com/BurntSushi/ripgrep/blob/44fb9fce2c1ee1a86...
- endorphine 4y agoAre there other examples of sum types besides enums, in Rust? Are the two terms synonymous?
- steveklabnik 4y agoRust 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.
- deleted 4y ago[deleted]