From 1966ee82073edb0934134620e7fda1652215498b 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..c012f7d 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 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); } ``` diff --git a/src/lib.rs b/src/lib.rs index 1c4060a..759bfe2 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 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: @@ -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]