about summary refs log tree commit diff
diff options
context:
space:
mode:
authorJacob Pratt <jacob@jhpratt.dev>2025-03-17 05:47:50 -0400
committerGitHub <noreply@github.com>2025-03-17 05:47:50 -0400
commit625278bb0e2224bb890243cc7f6af748c11e05b2 (patch)
tree20a75e703d1af10dc5dc205a7a29ed180e071c2e
parent62c2a7b93bfee720ce01a2ce6d7731f178213128 (diff)
parenta9b536f8a41e731b64b98e6c3085f2a7e4614504 (diff)
downloadrust-625278bb0e2224bb890243cc7f6af748c11e05b2.tar.gz
rust-625278bb0e2224bb890243cc7f6af748c11e05b2.zip
Rollup merge of #138341 - xizheyin:issue-138322, r=joboet
std: Mention clone-on-write mutation in Arc<T>

Fixes #138322

r? libs
-rw-r--r--library/alloc/src/sync.rs26
1 files changed, 23 insertions, 3 deletions
diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs
index 104cb35c23b..c62f8e5b70f 100644
--- a/library/alloc/src/sync.rs
+++ b/library/alloc/src/sync.rs
@@ -84,9 +84,29 @@ macro_rules! acquire {
 ///
 /// Shared references in Rust disallow mutation by default, and `Arc` is no
 /// exception: you cannot generally obtain a mutable reference to something
-/// inside an `Arc`. If you need to mutate through an `Arc`, use
-/// [`Mutex`][mutex], [`RwLock`][rwlock], or one of the [`Atomic`][atomic]
-/// types.
+/// inside an `Arc`. If you do need to mutate through an `Arc`, you have several options:
+///
+/// 1. Use interior mutability with synchronization primitives like [`Mutex`][mutex],
+///    [`RwLock`][rwlock], or one of the [`Atomic`][atomic] types.
+///
+/// 2. Use clone-on-write semantics with [`Arc::make_mut`] which provides efficient mutation
+///    without requiring interior mutability. This approach clones the data only when
+///    needed (when there are multiple references) and can be more efficient when mutations
+///    are infrequent.
+///
+/// 3. Use [`Arc::get_mut`] when you know your `Arc` is not shared (has a reference count of 1),
+///    which provides direct mutable access to the inner value without any cloning.
+///
+/// ```
+/// use std::sync::Arc;
+///
+/// let mut data = Arc::new(vec![1, 2, 3]);
+///
+/// // This will clone the vector only if there are other references to it
+/// Arc::make_mut(&mut data).push(4);
+///
+/// assert_eq!(*data, vec![1, 2, 3, 4]);
+/// ```
 ///
 /// **Note**: This type is only available on platforms that support atomic
 /// loads and stores of pointers, which includes all platforms that support