Skip to content

Commit

Permalink
docs: demonstrate ownedrefmut outliving scoped borrow
Browse files Browse the repository at this point in the history
  • Loading branch information
snormore committed Apr 28, 2024
1 parent e9150c4 commit 1966ee8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ fn main() {
// This is the major hazard of using `OwnedRefCell`.
let total: i32 = shared_map.borrow().values().sum();
assert_eq!(total, 116089);

// Note that OwnedRefMut outlives the scoped borrow, which would not compile
// when using RefCell/RefMut.
let map_ref = {
let mut map = shared_map.borrow_mut();
map.insert("purple", 1);
map
};
let total: i32 = map_ref.values().sum();
assert_eq!(total, 116090);
}
```

Expand Down
18 changes: 18 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@
//! // This is the major hazard of using `RefCell`.
//! let total: i32 = shared_map.borrow().values().sum();
//! assert_eq!(total, 116089);
//!
//! // Note that OwnedRefMut outlives the scoped borrow, which would not compile
//! // when using RefCell/RefMut.
//! let map_ref = {
//! let mut map = shared_map.borrow_mut();
//! map.insert("purple", 1);
//! map
//! };
//! let total: i32 = map_ref.values().sum();
//! assert_eq!(total, 116090);
//! ```
//!
//! This module also provides:
Expand Down Expand Up @@ -204,6 +214,14 @@ mod tests {

let total: i32 = shared_map.borrow().values().sum();
assert_eq!(total, 10);

let map_ref = {
let mut map = shared_map.borrow_mut();
map.insert("e", 5);
map
};
let total: i32 = map_ref.values().sum();
assert_eq!(total, 15);
}

#[test]
Expand Down

0 comments on commit 1966ee8

Please sign in to comment.