Created
April 11, 2025 06:59
-
-
Save oxalica/8029a482ca1607cbfdff0a279ace28f0 to your computer and use it in GitHub Desktop.
Singly linked list of mutable references, without heap allocation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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