为什么在 Rust 中强制不可变,除非你指定 mut
?这是安全的设计选择吗?您是否认为这在其他语言中应该是自然的?
我应该澄清一下,我仍然是 Rust 的新手。那么这是与语言中的另一个特性相关的设计选择吗?
最佳答案
Rust-Book实际上解决了这个主题。
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: addmut
.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.
基本上,C++ 的口头禅是您不想修改的所有内容都应该是 const,只需通过颠倒规则即可正确完成。 Also see this Stackoverflow article about C++.
关于rust - 除非用 `mut` 另行指定,否则为什么在 Rust 中强制执行不可变性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29631590/