liveBook · Manning

Arc

As explained in Rust Web Development

Arc is Rust’s atomically reference-counted shared pointer type, which allows multiple owners to access heap-allocated data.

Arc lets multithreaded REST handlers share one heap-allocated store instead of copying it or passing ownership between handlers. Cloning an Arc clones a pointer to the same data and atomically increments its reference count; when the last owner goes out of scope, the stored value is dropped. Arc provides shared ownership, not mutable access: pair the store with a Mutex or RwLock when handlers need to mutate it. section 4.2.1

Shared question store

A question store can hold questions as Arc<RwLock<HashMap<QuestionId, Question>>>. Handlers read the map through the lock while Arc shares the store.

Figure 4.3 Instead of dropping the value x, Rust increments the Arc count. Whenever x or y are going out of scope, Rust decreases the count until it is at 0, and then calls .drop to remove the value from the heap.
04-03

Shows how cloning an Arc increments its count and how the value is dropped when the count reaches zero. section 4.2.1

How Rust Web Development covers it

How deep it goes
Explains heap placement, pointer cloning, reference-count changes, and dropping at zero; defers mutation safety to locks.
Examples
Uses a HashMap-backed question store wrapped in Arc<RwLock<...>>.
What you can do after
Apply it by wrapping a shared store in Arc and pairing it with a lock when handlers need mutation.
How it connects
Pairs Arc with Tokio and RwLock, and contrasts it with single-threaded Rc.

Also explained in

Compare how 3 books explain Arc →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust Web Development. The section links point to the parts of the book it draws on.