Self-Referential Structs in Rust
ksnll.github.io·35w·
Discuss: Hacker News

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...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help