@@ -515,9 +515,45 @@ let x: int = 5;
515
515
```
516
516
517
517
If I asked you to read this out loud to the rest of the class, you'd say "` x `
518
- is a binding with the type ` int ` and the value ` five ` ." Rust requires you to
519
- initialize the binding with a value before you're allowed to use it. If
520
- we try...
518
+ is a binding with the type ` int ` and the value ` five ` ."
519
+
520
+ By default, bindings are ** immutable** . This code will not compile:
521
+
522
+ ``` {ignore}
523
+ let x = 5i;
524
+ x = 10i;
525
+ ```
526
+
527
+ It will give you this error:
528
+
529
+ ``` {ignore,notrust}
530
+ error: re-assignment of immutable variable `x`
531
+ x = 10i;
532
+ ^~~~~~~
533
+ ```
534
+
535
+ If you want a binding to be mutable, you can use ` mut ` :
536
+
537
+ ``` {rust}
538
+ let mut x = 5i;
539
+ x = 10i;
540
+ ```
541
+
542
+ There is no single reason that bindings are immutable by default, but we can
543
+ think about it through one of Rust's primary focuses: safety. If you forget to
544
+ say ` mut ` , the compiler will catch it, and let you know that you have mutated
545
+ something you may not have cared to mutate. If bindings were mutable by
546
+ default, the compiler would not be able to tell you this. If you _ did_ intend
547
+ mutation, then the solution is quite easy: add ` mut ` .
548
+
549
+ There are other good reasons to avoid mutable state when possible, but they're
550
+ out of the scope of this guide. In general, you can often avoid explicit
551
+ mutation, and so it is preferable in Rust. That said, sometimes, mutation is
552
+ what you need, so it's not verboten.
553
+
554
+ Let's get back to bindings. Rust variable bindings have one more aspect that
555
+ differs from other languages: bindings are required to be initialized with a
556
+ value before you're allowed to use it. If we try...
521
557
522
558
``` {ignore}
523
559
let x;
0 commit comments