Enums and Pattern Matching1
To run the program:
$ cargo run --bin enums-patterns
Compiling enums-patterns v0.1.0 ...
As I have some prior experience with enums and pattern matching from other languages (Ruby, OCaml, etc), the lessons learned here will be briefer than other sections.
Defining an enum
is easy:
enum IpAddressKind {
V4,
V6,
}
They are extra powerful when they contain semantic data:
enum IpAddress {
V4(u8, u8, u8, u8),
V6(String),
}
To retrieve values, use match
:
match ip_address {
V4(a, b, c, d) => println!("{a}.{b}.{c}.{d}"),
V6(e) => println!("{e}"),
}
Or, use if let
to handle a single case:
if let V4(a, b, c, d) = ip_address {
println!("{a}.{b}.{c}.{d}");
}