Self-Referential Structs in Rust
ksnll.github.io·28w·
Discuss: Hacker News
Preview
Report Post

Federico’s blog

Self-referential structs in Rust

31 May 2025 - 8 minutes read In Rust, there are a few paradigms that are more difficult to implement than in most other languages. Today, we’ll look at one of those: the self-referential structs. A self-referential struct contains a field that borrows from another field of the same struct. First of all, let’s start with a simple example of why we might want to use this kind of pattern. Let’s imagine we want to write a csv parser, but we want to avoid extra memory allocation. One way to do that could be to return pointers to the parsed fields, like so:

use std::io::{self, BufRead};
struct CsvRecord<'a> {
line: String,
fields: Vec<&'a str>,
}
fn load_record(line: String) -> CsvRecord<'_> {
let mut record...

Similar Posts

Loading similar posts...