Skip to content

fix(rust-patterns-book): make Lifetime Branding example compile#104

Open
rodrirejala wants to merge 1 commit into
microsoft:mainfrom
rodrirejala:fix/lifetime-branding-example
Open

fix(rust-patterns-book): make Lifetime Branding example compile#104
rodrirejala wants to merge 1 commit into
microsoft:mainfrom
rodrirejala:fix/lifetime-branding-example

Conversation

@rodrirejala
Copy link
Copy Markdown
Contributor

Fix #102
The Lifetime Branding example in ch04 failed to compile because alloc took
&'a mut self and returned ArenaHandle<'a>, keeping the mutable borrow alive.
Calling arena1.get(handle1) then tried to immutably borrow arena1 while it
was still mutably borrowed → error[E0502].
Solution: Use RefCell<Vec<String>> for interior mutability so alloc takes
&self instead of &mut self. The handle's lifetime is tied to an immutable
borrow, allowing get to coexist without borrow conflicts.
Changes:

  • Replace Vec<String> with RefCell<Vec<String>>
  • alloc: &'a mut self&self, use borrow_mut() for mutation
  • get: &'a self, ArenaHandle<'a> → &'a str → retains 'a constraint, returns String via clone
  • main: let mut arena1let arena1 (no longer needs mut)
    get returns a cloned String instead of &str — acceptable simplification for
    a teaching example focused on PhantomData and lifetime branding rather than
    zero-copy arena design.

Use RefCell for interior mutability so alloc takes &self instead of &mut self,
resolving the borrow checker conflict between alloc and get.
Fixes microsoft#102
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rust-patterns-book: ch04 Lifetime Branding example fails to compile due to borrow checker error

1 participant