Skip to content

Instantly share code, notes, and snippets.

@oxalica
Created April 11, 2025 06:59
Show Gist options
  • Save oxalica/8029a482ca1607cbfdff0a279ace28f0 to your computer and use it in GitHub Desktop.
Save oxalica/8029a482ca1607cbfdff0a279ace28f0 to your computer and use it in GitHub Desktop.
Singly linked list of mutable references, without heap allocation
use std::fmt::Debug;
// This won't work:
// struct Node<?> { this: usize, next: Option<&? mut Node<?>> }
trait Chain: Debug {
fn out(&mut self) -> Option<(&mut usize, &mut dyn Chain)>;
}
impl Chain for () {
fn out(&mut self) -> Option<(&mut usize, &mut dyn Chain)> {
None
}
}
impl Chain for (usize, &mut dyn Chain) {
fn out(&mut self) -> Option<(&mut usize, &mut dyn Chain)> {
Some((&mut self.0, self.1))
}
}
fn func(n: usize, chain: &mut dyn Chain) {
if n == 10 {
*chain.out().unwrap().1.out().unwrap().0 += 100;
dbg!(&chain);
} else {
func(n + 1, &mut (n, chain));
}
}
fn main() {
func(0, &mut ());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment