fix(rust-patterns-book): make Lifetime Branding example compile#104
Open
rodrirejala wants to merge 1 commit into
Open
fix(rust-patterns-book): make Lifetime Branding example compile#104rodrirejala wants to merge 1 commit into
rodrirejala wants to merge 1 commit into
Conversation
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
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fix #102
The Lifetime Branding example in ch04 failed to compile because
alloctook&'a mut selfand returnedArenaHandle<'a>, keeping the mutable borrow alive.Calling
arena1.get(handle1)then tried to immutably borrowarena1while itwas still mutably borrowed →
error[E0502].Solution: Use
RefCell<Vec<String>>for interior mutability soalloctakes&selfinstead of&mut self. The handle's lifetime is tied to an immutableborrow, allowing
getto coexist without borrow conflicts.Changes:
Vec<String>withRefCell<Vec<String>>alloc:&'a mut self→&self, useborrow_mut()for mutationget:&'a self, ArenaHandle<'a> → &'a str→ retains'aconstraint, returnsStringvia clonemain:let mut arena1→let arena1(no longer needs mut)getreturns a clonedStringinstead of&str— acceptable simplification fora teaching example focused on PhantomData and lifetime branding rather than
zero-copy arena design.