Ross A. Baker

@rossabaker.com

Never daunted. #Rustlang #Python #Typelevel #Emacs #Nix #Indieweb Languages: en,de,es 🌉 bridged from ⁂ https://social.rossabaker.com/@ross, follow @ap.brid.gy to interact

Up until 2am the night before Labor Day preparing security releases and barbecue. Those who pointed their Slop-o-Matic 2000™ at me will receive credit in the CVEs but are ineligible for my smoked salmon.

A colleague wondered if he is safer from phishing attacks by not updating his LinkedIn for a few years. I think he just invented the resume cooldown period.

A key difference between me now and me 25 years ago is that now I'm compiling Emacs at 6:30am because I'm up early instead of compiling Emacs at 6:30am because I'm up late.

As the weather guy for a soccer league in Indiana, I've been missing the balloons we used to launch over the Great Plains. It's not just the weather that's getting worse: it's also our ability to forecast it.

I was the guitarist of a band called the Damn Pigeons in high school. We had no songs, talent, or transportation to even all meet together at once. But our first album would have been called "Don't Shit on my Sidewalk" and it would have been fucking rad.

Rust Book for Scala Developers, Chapter 7: packages, crates, and modules https://rossabaker.com/blog/rust-book-ch07/ #Rust #Scala

Rust Book, Chapter 7: Packages, Crates, and Modules

The way Rust organizes code can be tricky for Scala developers. The concepts do not map one-to-one. Further confusing matters, Rust packages are not the closest thing to Scala packages. There are loose translations to Scala to help us get our bearings. ## Packages and crates # In Rust, a crate is the unit of compilation. It’s either a binary crate or a library crate. The binary artifact is either one executable or one library. It’s a bit like a Scala `.class`, which is runnable if it’s an object with the right `main` signature, or may be added to the classpath to be loaded and linked with other code. A crate is coarser: multiple Rust files may compile into one crate, while it’s common for a single Scala file to compile into multiple clases. Rust crates are bundled into a package. It may have multiple binary crates and optionally a library crate. This is close to a Scala `.jar`, which bundles library classes, any number of which may be runnable. ## Modules # A Rust module is closer to Scala packages than Rust packages are. It’s a means to organize code into logical namespaces. Scala pcakages are typically organized into files according to Java conventions, but a single package can be split across arbitrary files on the source path. Rust modules are more prescriptive: the module name is reflected in the filename, and the hierarchy in the directory structure. ### Visibility # In Rust, visibility is private by default. In Scala, it’s public. If a definition is public in Scala, it can be imported and accessed anywhere. The Rust equivalent is `pub` on the definition within the module plus `pub mod` where the module is included. If a module is included with `mod` instead of `pub mod`, it’s similar to declaring it package private in Scala. Because Rust does not have subtyping, we are spared the complications of Scala’s `protected`. ## `use` # Rust’s `use` is about like Scala’s `import`, where `::` is the delimiter instead of `.`. Importing the full path of structs and enums in Rust is idiomatic, but that functions are typically referenced via their parent. This is different from Scala, where functions are often imported into the current scope either to be found implicitly or to be referenced tersely. Rust has `pub use` to re-export definitions as though they originated in the using package. Scala 3 introduces `export` for similar functionality, but it requires manual forwarders in Scala 2. The wildcard import in Rust is `*`. Scala 2 uses `_`, but many projects use `*` via a compiler flag for Scala 3 compatibility. ## `foo.rs` vs. `foo/mod.rs` # Rust allows module `foo` to be declared in either `foo.rs` or `foo/mod.rs`. Scala package objects may similarly live in either `foo.scala` or `foo/package.scala`, but also `something/nonsensical.scala`. The book prefers `foo.rs`, but not all Rust developers agree. If `foo` has its own submodules, it will be a directory anyway, and `foo/mod.rs` is nice. Some developers may find many files named `mod.rs` awkward, and it’s more common than `package.scala`. My opinion in both Rust and Scala is agree to one convention on the project, be consistent, and pick your battles elsewhere.

rossabaker.com

Rust for Scala Developers, Chapter 6, on `enum`. https://rossabaker.com/blog/rust-book-ch06/ Not new if you follow my RSS, but I just added a section on how Rust variants are not types. #Rust #Scala

Rust Book, Chapter 6: Enums and Pattern Matching

Chapter 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!

rossabaker.com