-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: mutate in closure with refcell
- Loading branch information
1 parent
cd28253
commit 9f39503
Showing
3 changed files
with
24 additions
and
3 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,2 @@ | ||
pub mod mutate_in_closure; | ||
pub mod vec_any; | ||
|
||
pub use vec_any::Animal; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
use std::cell::RefCell; | ||
|
||
// Use RefCell to mutate a variable in a closure | ||
pub fn mutate_in_closure() { | ||
let my_string = RefCell::new("hello".to_string()); | ||
let mutate = |new_val| { | ||
*my_string.borrow_mut() = new_val; | ||
}; | ||
// mutate in closure | ||
mutate("hej".to_string()); | ||
assert_eq!(*my_string.borrow(), "hej"); | ||
|
||
*my_string.borrow_mut() = "bonjour".to_string(); | ||
assert_eq!(*my_string.borrow(), "bonjour"); | ||
} | ||
|
||
mod tests { | ||
#[test] | ||
fn test_mutate_in_closure() { | ||
super::mutate_in_closure(); | ||
} | ||
} |