How to Make Only Certain Struct Fields Mutable in Rust: Mutably Borrowing Specific Fields Explained
In Rust, the ownership and borrowing system is designed to enforce memory safety at compile time. A core tenet of this system is that data is either immutable or mutable—but not both simultaneously. When working with structs, this often means that if you want to mutate any field, the entire struct must be marked as mut. However, real-world scenarios frequently demand more granular control: perhaps you want an id field to remain immutable for consistency, while a login_count field should be freely updatable.
This blog post explores how to achieve selective mutability for struct fields in Rust. We’ll break down the challenges of limiting mutations to specific fields, examine practical solutions (including interior mutability with Cell/RefCell and concurrency primitives like Mutex), and provide actionable examples to help you implement these patterns in your code.
Table of Contents#
- Understanding Mutable and Immutable Structs in Rust
- The Challenge: Limiting Mutation to Specific Fields
- Solutions for Mutably Borrowing Specific Fields
- Examples in Action: A Practical Use Case
- Common Pitfalls and How to Avoid Them
- Conclusion
- References
Understanding Mutable and Immutable Structs in Rust#
By default, Rust enforces strict mutability rules for structs:
- An immutable struct (defined without
mut) has all fields immutable. Attempting to modify any field will result in a compile error. - A mutable struct (defined with
mut) allows modification of all fields, but requires a mutable reference (&mut self) to do so.
Example: Default Struct Mutability#
struct User {
id: u64,
name: String,
login_count: u32,
}
fn main() {
// Immutable struct: all fields are immutable
let alice = User {
id: 1,
name: "Alice".to_string(),
login_count: 0,
};
alice.login_count += 1; // ❌ Compile error: cannot assign to immutable field `login_count`
// Mutable struct: all fields are mutable
let mut bob = User {
id: 2,
name: "Bob".to_string(),
login_count: 0,
};
bob.login_count += 1; // ✅ Works: `bob` is mutable
bob.id = 3; // ✅ Also works: all fields are mutable
}This all-or-nothing approach is restrictive. What if we want login_count to be mutable but id and name to remain immutable? This is where selective mutability comes into play.
The Challenge: Limiting Mutation to Specific Fields#
Consider a User struct where:
idandnameare set once at creation and should never change (immutable).login_countneeds to be incremented every time the user logs in (mutable).
With default Rust rules, marking User as mut would allow accidental modification of id or name, which we want to prevent. We need a way to isolate mutability to specific fields without making the entire struct mutable.
Solutions for Mutably Borrowing Specific Fields#
Rust provides several strategies to achieve selective mutability. We’ll explore the most common ones, starting with interior mutability primitives.
1. Interior Mutability with Cell (for Copy Types)#
The Cell<T> type (from std::cell) enables interior mutability for Copy types (e.g., u32, bool, f64). It allows mutation of data even when the struct itself is immutable, by storing a copy of the data and providing get() and set() methods to read/write values.
How It Works:#
Cell<T>is only valid forT: Copy(since it copies data onget()).- It does not provide references to the inner data (avoids borrow checker issues).
Example: Using Cell for login_count#
use std::cell::Cell;
struct User {
id: u64, // Immutable (no Cell)
name: String, // Immutable (no Cell)
login_count: Cell<u32>, // Mutable (wrapped in Cell)
}
impl User {
fn new(id: u64, name: String) -> Self {
User {
id,
name,
login_count: Cell::new(0), // Initialize Cell with 0
}
}
// Increment login_count (no `&mut self` needed!)
fn increment_login(&self) {
let current = self.login_count.get(); // Copy current value
self.login_count.set(current + 1); // Set new value
}
// Get login_count (returns a copy)
fn get_login_count(&self) -> u32 {
self.login_count.get()
}
}
fn main() {
// Create an IMMUTABLE User instance
let alice = User::new(1, "Alice".to_string());
// Mutate login_count WITHOUT a mutable struct!
alice.increment_login();
alice.increment_login();
println!("Alice's login count: {}", alice.get_login_count()); // Output: 2
// Try to mutate id (still immutable)
alice.id = 2; // ❌ Compile error: cannot assign to immutable field `id`
}Why This Works: login_count is wrapped in Cell<u32>, which allows mutation via set(), even though alice is immutable. id and name remain immutable because they are not wrapped in Cell.
2. Interior Mutability with RefCell (for Non-Copy Types)#
For non-Copy types (e.g., String, Vec<T>, custom structs), RefCell<T> (also from std::cell) is the go-to choice. Unlike Cell, RefCell allows borrowing references to the inner data, but checks borrow rules at runtime (instead of compile time) to ensure safety.
Key Methods:#
borrow(&self) -> Ref<T>: Returns an immutable reference to the inner data (panics if already borrowed mutably).borrow_mut(&self) -> RefMut<T>: Returns a mutable reference to the inner data (panics if already borrowed immutably or mutably).try_borrow(&self) -> Result<Ref<T>, BorrowError>: Non-panicking version ofborrow.try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError>: Non-panicking version ofborrow_mut.
Example: Using RefCell for a String Field#
use std::cell::RefCell;
struct User {
id: u64, // Immutable
name: String, // Immutable
last_login: RefCell<Option<String>>, // Mutable (non-Copy type)
}
impl User {
fn new(id: u64, name: String) -> Self {
User {
id,
name,
last_login: RefCell::new(None), // Initialize with None
}
}
// Update last_login with a timestamp (non-Copy type)
fn set_last_login(&self, timestamp: String) {
// Use borrow_mut() to get a mutable reference to the inner Option<String>
*self.last_login.borrow_mut() = Some(timestamp);
}
// Get last_login (immutable borrow)
fn get_last_login(&self) -> Option<String> {
// Clone the inner String (since we can't return a reference from RefCell)
self.last_login.borrow().clone()
}
}
fn main() {
let alice = User::new(1, "Alice".to_string());
// Update last_login (mutable borrow)
alice.set_last_login("2024-05-20 14:30".to_string());
// Read last_login (immutable borrow)
println!("Last login: {:?}", alice.get_last_login()); // Output: Some("2024-05-20 14:30")
// Attempt to borrow mutably while already borrowed immutably (PANICS!)
let login_ref = alice.last_login.borrow(); // Immutable borrow
alice.last_login.borrow_mut(); // ❌ Panics: "already borrowed: BorrowMutError"
}Note: To avoid panics in production, use try_borrow_mut() and handle errors:
fn safe_set_last_login(&self, timestamp: String) -> Result<(), String> {
let mut last_login = self.last_login.try_borrow_mut()
.map_err(|e| format!("Failed to borrow: {}", e))?;
*last_login = Some(timestamp);
Ok(())
}3. Concurrency: Mutex and RwLock for Multi-Threaded Code#
Cell and RefCell are not thread-safe (they do not implement Sync). For multi-threaded scenarios, use Mutex<T> (mutual exclusion) or RwLock<T> (read-write lock) from std::sync. These primitives enforce exclusive access to mutable data across threads.
Example: Mutex for Thread-Safe Mutation#
use std::sync::Mutex;
use std::thread;
struct Counter {
id: u32, // Immutable
count: Mutex<u32>, // Mutable (thread-safe)
}
impl Counter {
fn new(id: u32) -> Self {
Counter {
id,
count: Mutex::new(0),
}
}
fn increment(&self) {
// Lock the mutex to get mutable access (blocks until available)
let mut count = self.count.lock().unwrap();
*count += 1;
}
fn get_count(&self) -> u32 {
*self.count.lock().unwrap()
}
}
fn main() {
let counter = Counter::new(1);
let counter_ref = &counter; // Shared reference across threads
// Spawn 10 threads to increment the counter
let handles: Vec<_> = (0..10)
.map(|_| {
thread::spawn(move || {
counter_ref.increment();
})
})
.collect();
// Wait for all threads to finish
for handle in handles {
handle.join().unwrap();
}
println!("Final count: {}", counter.get_count()); // Output: 10
}Why This Works: Mutex ensures only one thread can mutate count at a time, preventing race conditions. id remains immutable and can be safely shared across threads.
4. Splitting the Struct into Multiple Parts#
For cases where interior mutability feels overkill, split the struct into immutable and mutable components with separate ownership. This works well when you can isolate mutable fields into a sub-struct.
Example: Splitting a Struct#
// Immutable part: never changes
struct UserData {
id: u64,
name: String,
}
// Mutable part: can be modified
struct UserStats {
login_count: u32,
}
// Combine them into a User
struct User {
data: UserData,
stats: UserStats,
}
impl User {
fn new(id: u64, name: String) -> Self {
User {
data: UserData { id, name },
stats: UserStats { login_count: 0 },
}
}
// Get immutable data
fn data(&self) -> &UserData {
&self.data
}
// Get mutable stats
fn stats_mut(&mut self) -> &mut UserStats {
&mut self.stats
}
}
fn main() {
let mut alice = User::new(1, "Alice".to_string());
// Access immutable data (no `mut` needed)
println!("ID: {}", alice.data().id); // Output: 1
// Mutate stats via mutable reference
alice.stats_mut().login_count += 1;
println!("Login count: {}", alice.stats.login_count); // Output: 1
// Attempt to mutate data (compile error)
alice.data().id = 2; // ❌ Compile error: cannot assign to immutable field `id`
}Tradeoff: This requires passing &mut UserStats explicitly, which may complicate APIs compared to interior mutability.
Examples in Action: A Practical Use Case#
Let’s build a Cache struct with selective mutability:
max_size(immutable): The maximum number of entries the cache can hold.current_size(mutable): Tracks the current number of entries (usesCell<usize>).entries(mutable): A hash map of cached values (usesRefCell<HashMap<K, V>>).
Example: Selective Mutability in a Cache#
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
struct Cache<K, V> {
max_size: usize, // Immutable
current_size: Cell<usize>, // Mutable (Copy type)
entries: RefCell<HashMap<K, V>>, // Mutable (non-Copy type)
}
impl<K: Eq + std::hash::Hash, V> Cache<K, V> {
fn new(max_size: usize) -> Self {
Cache {
max_size,
current_size: Cell::new(0),
entries: RefCell::new(HashMap::new()),
}
}
fn insert(&self, key: K, value: V) -> Option<V> {
let mut entries = self.entries.borrow_mut();
let prev_size = entries.len();
let result = entries.insert(key, value);
// Update current_size only if a new entry was added
if result.is_none() {
self.current_size.set(prev_size + 1);
}
// Evict oldest entry if over max_size (simplified)
if self.current_size.get() > self.max_size {
entries.clear();
self.current_size.set(0);
}
result
}
fn get(&self, key: &K) -> Option<&V> {
self.entries.borrow().get(key)
}
fn size(&self) -> usize {
self.current_size.get()
}
}
fn main() {
let cache = Cache::new(2); // max_size = 2 (immutable)
cache.insert("a", 1);
cache.insert("b", 2);
println!("Size: {}", cache.size()); // Output: 2
cache.insert("c", 3); // Exceeds max_size; cache is cleared
println!("Size: {}", cache.size()); // Output: 0
println!("Get 'a': {:?}", cache.get(&"a")); // Output: None (evicted)
}Here, max_size is immutable, while current_size and entries are mutable via Cell and RefCell, respectively. The cache can be modified without being marked mut.
Common Pitfalls and How to Avoid Them#
| Pitfall | Solution |
|---|---|
Using Cell with non-Copy types | Use RefCell instead (for single-threaded) or Mutex (for multi-threaded). |
RefCell panics on borrow conflicts | Use try_borrow()/try_borrow_mut() and handle BorrowError/BorrowMutError. |
Cell/RefCell in multi-threaded code | Replace with Mutex or RwLock (they implement Sync). |
| Overusing interior mutability | Prefer regular mut references when possible—interior mutability makes code harder to reason about. |
Forgetting to lock Mutex/RwLock | Always call lock()/read()/write() before accessing the inner data (use unwrap() for prototyping, expect() with messages for production). |
Conclusion#
Selective mutability in Rust allows you to isolate mutations to specific struct fields, enhancing safety and reducing bugs. Choose the right tool for the job:
Cell<T>: ForCopytypes in single-threaded code.RefCell<T>: For non-Copytypes in single-threaded code (usetry_*methods to avoid panics).Mutex<T>/RwLock<T>: For thread-safe mutation in multi-threaded code.- Struct splitting: For simple cases where you want to separate ownership of mutable and immutable data.
Use interior mutability judiciously—it’s a powerful tool, but overuse can make code harder to debug. When in doubt, start with regular mut references and refactor to interior mutability only when needed.