Starting a Newsletter with Rust
A sample post that exercises every Markdown feature the site supports.
Welcome to the sample post. Every post has two parts: a Build Log about what I worked on this week, and a Concept of the Week that digs into one idea in depth.
Build Log
This week I got Markdown files turning into full HTML pages. The pipeline reads posts from content/, parses the frontmatter, renders the body, and writes each page to public/post-N/index.html.
What went well:
- Frontmatter parses into a typed struct with serde
- Errors are returned instead of panicking
Sorting by dateSorting by post ID, newest first
What's left:
- Render a single post
- Shared base layout
- Index page
- RSS feed
The hardest bug was a lifetime error when sorting:
// Doesn't compile: the closure returns a reference into each element.
posts.sort_by_key(|p| p.meta_data().id());
// Compiles: the key is an owned copy.
posts.sort_by_key(|p| *p.meta_data().id());
sort_by_keyneeds a key that doesn't borrow from the element, because the sort moves elements around in memory.
Concept of the Week: Ownership
In Rust, every value has exactly one owner. When the owner goes out of scope, the value is dropped. You can lend a value out with references:
- Any number of shared references (
&T), or - Exactly one mutable reference (
&mut T)
...but never both at the same time.
| Concept | C++ analogy | Rust |
|---|---|---|
| Owned string | std::string | String |
| Borrowed view | std::string_view | &str |
| Dangling ref | Undefined behavior | Compile error |
The borrow checker isn't stopping you from writing programs. It's stopping you from writing some programs, and most of those were bugs.
Returning a reference to a local variable is the classic dangling reference. See Rust Book Ch. 4.2.
Some math for later: the number of windows in a list of n items is n - 1, and
\sum_{i=1}^{n} i = \frac{n(n+1)}{2}
Thanks for reading. See you next week.