rust - 除非用 `mut` 另行指定,否则为什么在 Rust 中强制执行不可变性?

标签 rust immutability

为什么在 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: 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.

基本上,C++ 的口头禅是您不想修改的所有内容都应该是 const,只需通过颠倒规则即可正确完成。 Also see this Stackoverflow article about C++.

关于rust - 除非用 `mut` 另行指定,否则为什么在 Rust 中强制执行不可变性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29631590/

相关文章:

javascript - 我在改变 reducer 中的 redux 状态吗?

multithreading - 线程化 DES 比非线程化慢

rust - 如何将返回值的生命周期设置为我移入其中的变量的生命周期?

python - Cython 具体化属性?

haskell - Haskell 中的纯函数是否有可能改变变量的本地副本?

java - immutableList 但仍然可以修改列表中的元素

java - 如何确定一个类是否不可变

rust - 从读取到写入的最简单方法是什么

rust - 如何使用宏根据架构定义具有不同调用约定的函数?

rust - 如何根据构建配置文件切换依赖项