From 3d206ba986975c90f6309dfb56dcb8d93d28d49e Mon Sep 17 00:00:00 2001 From: Steven Normore Date: Sun, 28 Apr 2024 19:05:18 -0400 Subject: [PATCH] docs: demonstrate ownedrefmut outliving scoped borrow --- README.md | 10 ++++++++++ src/lib.rs | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/README.md b/README.md index a7865a1..99d48e2 100644 --- a/README.md +++ b/README.md @@ -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 the `OwnedRefMut` outlives the scoped borrow, which would not + // compile as a `RefMut` when using `RefCell`. + 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); } ``` diff --git a/src/lib.rs b/src/lib.rs index 1c4060a..1a167c5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 the `OwnedRefMut` outlives the scoped borrow, which would not +//! // compile as a `RefMut` when using `RefCell`. +//! 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: @@ -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]