rossabaker.comRust Book, Chapter 6: Enums and Pattern MatchingChapter Six
I am still primarily a Scala 2 developer, so Iβll continue to lean into sealed traits in these examples. Scala 3 `enum` covers many of the same ideas, and in a syntax closer to Rustβs!
## Defining an enum #
A Rust enum implements sum types, as Scala 2 does with sealed traits. The variants `V4` and `V6` are like the case classes and objects that extend the trait.
CC-BY-SA-4.0
enum IpAddrKind {
V4,
V6,
}
CC-BY-SA-4.0
sealed trait IpAddrKind
object IpAddrKind {
case object V4 extends IpAddrKind
case object V6 extends IpAddrKind
}
All the struct types we saw in the previous chapter are available here. The Scala `Write` is not a zero-cost newtype like Rustβs mostly to avoid a lengthy digression into Scala 2βs various encodings and tradeoffs.
CC-BY-SA-4.0
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
CC-BY-SA-4.0
sealed trait Message {
case object Quit extends Message
case class Move(x: Int, y: Int) extends Message
case class Write(value: String) extends Message
case class ChangeColor(r: i32, g: i32, b: i32) extends Message
}
### `Option` #
Rustβs `Option` is familiar to Scalaβs.
CC-BY-SA-4.0
enum Option<T> {
None,
Some(T),
}
CC-BY-SA-4.0
sealed trait Option[+A]
case class Some[+A](a: A) extends Option[A]
case object None extends Nothing
A couple headaches are gone in Rust:
* Rust has no `null`, so there is no `Some(null)`. This doesnβt come up often in practice in Scala, but itβs a cost of Java interop.
* No variance or quirks thereof!
## Pattern matching #
Rustβs pattern matching is syntactically different from Scalaβs, but conceptually almost identical. As a new Rustacean, this made it frustrating to write but intuitive to read. The important bits are the same:
* Matches are exhaustive. This is good today when you forget one, and great tomorrow when you add another variant and the compiler tells you what you need to fix everywhere in your app.
* Matches can bind values: `Some(x) =>` safely gets `x` out of the `Option` if and only if itβs `Some`. The only tricky bit here is that Rustβs ownership rules still apply.
* Literal values can be matched.
## Rust variants are not types #
Scalaβs sealed trait model is based on on subtyping. `Some(42)` is both a `Some` and `Option`. `None` is both a `None.type` and `Option`.
Rust enums are more like having just `apply` and `unapply`: we can construct and pattern match `Some` and `None`, but because there is no subtyping, the values have just one type: `Option`.
### Nested sum types #
Scalaβs model easily extends to multiple levels. A URI may have an authority, which is either a registered name or an IP address. The IP address may be either IPv4 or IPv6.
CC-BY-SA-4.0
sealed trait Authority
case class RegName(value: String) extends Authority
sealed trait Ip extends Authority
case class IpV4(β¦) extends Ip
case class IpV6(β¦) extends Ip
We can just as easily define functions that accept or return `Authority`, `Ip`, and `IpV4`, operating at the right level of abstraction for the task at hand.
In practice, what Rust gives us is often enough: how often does a Scala signature explicitly refer to `Some` or `None.type`? In cases that itβs not enough, we can define structs for each concrete data type, and then each variant can wrap either a struct or another enum.
CC-BY-SA-4.0
enum Authority {
RegName(RegName),
Ip(Ip),
}
enum Ip {
IpV4(IpV4),
IpV6(IpV6),
};
struct RegName(String);
struct IpV4(u32)
struct IpV6(u64, u64);
## Control flow #
Rust has two control flow syntaxes that are unfamiliar to Scala developers.
### `if...let` #
Rust:
CC-BY-SA-4.0
let config_max = Some(3u8);
if let Some(max) = config_max {
println!("The maximum is configured to be {max}");
}
In Scala, we have to explicitly map the `None` to `()`.
CC-BY-SA-4.0
val configMax: Option[Int] = Some(3)
configMatch match {
case Some(max) => println("The maximum is configured to be {max}")
case None => ()
}
As a functional Scala developer, Iβd use `IO`.
#+begin_aside Iβd actually use `Console[F]`, but weβre here to learn Rust, not fight the old Scala wars. println(βThe maximum is configured to be {max}β)#+end_aside
CC-BY-SA-4.0
val configMax: Option[Int] = Some(3)
configMatch match {
case Some(max) => IO.println("The maximum is configured to be {max}")
case None => IO.unit
}
Because `Option` can be traversed and `IO` is applicative, we can turn the `Option` into an `IO` by giving a function of what might be in the `Option` (`Int`) to `IO`:
CC-BY-SA-4.0
configMatch.traverseVoid(max => IO.println(s"The maximum is configured to be $max"))
Imperative Scala is more verbose than Rust in this case, but once we get back to working with pure values, Cats can be more concise!