Have you ever wanted to write a structurally typed function in Rust? Do you spend a lot of time and effort getting your Rust structs just so, and want

Structural Typing in Rust

submited by
Style Pass
2021-05-28 15:00:39

Have you ever wanted to write a structurally typed function in Rust? Do you spend a lot of time and effort getting your Rust structs just so, and want to DRY-out data access for common field paths without declaring a new trait and implementing it for each struct (let’s say, Cat and Dog both have a name: String field)? If so, read on.

This post talks about how we can leverage LabelledGeneric to build Path traversers (functionally similar to lenses), and use them to write clean and performant structurally typed functions with all the compile-time safety that you’ve come to expect from Rust.

Lastly, I just didn’t have the oomph to write a post that describes transmogrify() to follow up on the post on Struct transforms. Transmogrifier, which allows flexibile recursive transformation between similarly-structured structs, was added over 2.5 years ago, but writing about it was … intimidating.

Still, I recently decided to try to start writing again, so I picked a topic that’s slightly simpler, but related: Path, which introduced zero-overhead structurally-typed functions that you could use with normal structs to stable Rust back in Februrary of 2019 1.

Leave a Comment