Why is immutability enforced in Rust unless otherwise specified with `mut`?

谁说我不能喝 提交于 2020-06-13 15:34:08

问题


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?


回答1:


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++.



来源:https://stackoverflow.com/questions/29631590/why-is-immutability-enforced-in-rust-unless-otherwise-specified-with-mut

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!