22

Why is immutability forced in Rust, unless you specify mut? Is this a design choice for safety, do you consider this how it should be naturally in other languages?

I should probably clarify, I'm still a newbie at Rust. So is this a design choice related to another feature in the language?

metro-man
  • 1,763
  • 2
  • 15
  • 28
  • Do you ask whether it's important to track mutability, or are you already convinced that tracking mutability is important and only want to know whether immutability is the default? – Matthieu M. Apr 14 '15 at 15:55
  • Uhhh, I've updated the question a little bit. What do you mean by tracking mutability? – metro-man Apr 14 '15 at 15:56
  • Actually, Rust doesn't enforce interior mutability. What it does check is you can't call `&mut` method on something that wasn't declared `mut`. You can still change `Cell` or `RefCell` using immutable borrow. – Daniel Fath Apr 15 '15 at 08:54

1 Answers1

25

The Rust-Book actually addresses this topic.

There is no single reason that bindings are immutable by default, but we can think about it through one of Rust’s primary focuses: safety. If you forget to say mut, the compiler will catch it, and let you know that you have mutated something you may not have intended to mutate. If bindings were mutable by default, the compiler would not be able to tell you this. If you did intend mutation, then the solution is quite easy: add mut.

There are other good reasons to avoid mutable state when possible, but they’re out of the scope of this guide. In general, you can often avoid explicit mutation, and so it is preferable in Rust. That said, sometimes, mutation is what you need, so it’s not verboten.

Basically it is the C++-Mantra that everything that you don't want to modify should be const, just properly done by reversing the rules. Also see this Stackoverflow article about C++.

Community
  • 1
  • 1
oli_obk
  • 28,729
  • 6
  • 82
  • 98
  • 2
    Perfect, I probably should have checked their reference/specification/book before posting this :) – metro-man Apr 14 '15 at 16:01
  • 1
    Another point: Every time someone measured it, the majority of bindings were immutable. Assuming we're already sold on tracking mutable vs immutable bindings precisely, then marking the mutable ones and making immutable the default is the economic choice, as it uses less code than the other way around. –  Apr 14 '15 at 16:23
  • 6
    Not just majority, but overwhelming majority. A non-scientific test: I just grabbed Cargo's source, and there are 356 instances of 'let mut', and 1937 instances of 'let' (which of course counts let mut too, so 1581 pure lets). – Steve Klabnik Apr 14 '15 at 17:11
  • 4
    that doesn't even count function arguments. I'd wager the ratio is even larger when function args are included – oli_obk Apr 15 '15 at 09:02