3 Mutability, the ability to change something, works a bit differently in Rust
4 than in other languages. The first aspect of mutability is its non-default
12 We can introduce mutability with the `mut` keyword:
20 This is a mutable [variable binding][vb]. When a binding is mutable, it means
21 you’re allowed to change what the binding points to. So in the above example,
22 it’s not so much that the value at `x` is changing, but that the binding
23 changed from one `i32` to another.
25 [vb]: variable-bindings.html
27 If you want to change what the binding points to, you’ll need a [mutable reference][mr]:
34 [mr]: references-and-borrowing.html
36 `y` is an immutable binding to a mutable reference, which means that you can’t
37 bind `y` to something else (`y = &mut z`), but you can mutate the thing that’s
38 bound to `y` (`*y = 5`). A subtle distinction.
40 Of course, if you need both:
47 Now `y` can be bound to another value, and the value it’s referencing can be
50 It’s important to note that `mut` is part of a [pattern][pattern], so you
51 can do things like this:
54 let (mut x, y) = (5, 6);
60 [pattern]: patterns.html
62 # Interior vs. Exterior Mutability
64 However, when we say something is ‘immutable’ in Rust, that doesn’t mean that
65 it’s not able to be changed: We mean something has ‘exterior mutability’. Consider,
66 for example, [`Arc<T>`][arc]:
75 [arc]: ../std/sync/struct.Arc.html
77 When we call `clone()`, the `Arc<T>` needs to update the reference count. Yet
78 we’ve not used any `mut`s here, `x` is an immutable binding, and we didn’t take
79 `&mut 5` or anything. So what gives?
81 To understand this, we have to go back to the core of Rust’s guiding
82 philosophy, memory safety, and the mechanism by which Rust guarantees it, the
83 [ownership][ownership] system, and more specifically, [borrowing][borrowing]:
85 > You may have one or the other of these two kinds of borrows, but not both at
88 > * one or more references (`&T`) to a resource.
89 > * exactly one mutable reference (`&mut T`)
91 [ownership]: ownership.html
92 [borrowing]: borrowing.html#The-Rules
94 So, that’s the real definition of ‘immutability’: is this safe to have two
95 pointers to? In `Arc<T>`’s case, yes: the mutation is entirely contained inside
96 the structure itself. It’s not user facing. For this reason, it hands out `&T`
97 with `clone()`. If it handed out `&mut T`s, though, that would be a problem.
99 Other types, like the ones in the [`std::cell`][stdcell] module, have the
100 opposite: interior mutability. For example:
103 use std::cell::RefCell;
105 let x = RefCell::new(42);
107 let y = x.borrow_mut();
110 [stdcell]: ../std/cell/index.html
112 RefCell hands out `&mut` references to what’s inside of it with the
113 `borrow_mut()` method. Isn’t that dangerous? What if we do:
116 use std::cell::RefCell;
118 let x = RefCell::new(42);
120 let y = x.borrow_mut();
121 let z = x.borrow_mut();
125 This will in fact panic, at runtime. This is what `RefCell` does: it enforces
126 Rust’s borrowing rules at runtime, and `panic!`s if they’re violated. This
127 allows us to get around another aspect of Rust’s mutability rules. Let’s talk
130 ## Field-level mutability
132 Mutability is a property of either a borrow (`&mut`) or a binding (`let mut`).
133 This means that, for example, you cannot have a [`struct`][struct] with
134 some fields mutable and some immutable:
143 The mutability of a struct is in its binding:
151 let mut a = Point { x: 5, y: 6 };
155 let b = Point { x: 5, y: 6};
157 b.x = 10; // error: cannot assign to immutable field `b.x`
160 [struct]: structs.html
162 However, by using `Cell<T>`, you can emulate field-level mutability:
172 let point = Point { x: 5, y: Cell::new(6) };
176 println!("y: {:?}", point.y);
179 This will print `y: Cell { value: 7 }`. We’ve successfully updated `y`.