Skip to content

Commit

Permalink
feat: mutate in closure with refcell
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandervantrijffel committed Oct 12, 2024
1 parent cd28253 commit 9f39503
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pipeline.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ jobs:
token: ${{ secrets.GITHUB_TOKEN }}

- name: Test
run: cargo test --verbose
run: cargo test --release --verbose

build:
if: "!contains(github.event.head_commit.message, 'NO_CI')"
Expand Down
3 changes: 1 addition & 2 deletions src/lib.rs
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;
22 changes: 22 additions & 0 deletions src/mutate_in_closure.rs
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();
}
}

0 comments on commit 9f39503

Please sign in to comment.