How to make a field immutable?
⚓ Rust 📅 2026-01-15 👤 surdeus 👁️ 2Access fields unmutably.
Let's say I have a struct:
struct Foo
{
pub a : A,
pub b : B,
}
and a function:
fn bar(a : &A, b : &mut B).
I want Foo.a to be immutable. However, if I were to make it private and write an immutable accessor, then I couldn't call:
bar(&foo.a, &mut foo.b)
anymore, since the accessor
fn get_a(&self) -> &A { &self.a }
would borrow the entire Foo on a call.
How do I work around this without creating a function which borrows every field (some mutable and some immutable, depending on which fields should remain unmutated)?
7 posts - 6 participants
🏷️ Rust_feed