Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 767
metro-man Avatar asked Apr 14 '15 15:04

metro-man


People also ask

Why is Rust immutable by default?

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.

What is Mut in Rust?

mut stands for mutable. You are telling the Rust compiler that you will be changing this variable. What's nice is that Rust holds you to this contract. If you declare a variable using mut and never change it you'll see this warning.

How do you make a mutable variable in Rust?

Although variables are immutable by default, you can make them mutable by adding mut in front of the variable name as you did in Chapter 2. Adding mut also conveys intent to future readers of the code by indicating that other parts of the code will be changing this variable's value.

What is a mutable reference in Rust?

Back to Rust. A mutable reference is a borrow to any type mut T , allowing mutation of T through that reference. The below code illustrates the example of a mutable variable and then mutating its value through a mutable reference ref_i .


1 Answers

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

like image 195
oli_obk Avatar answered Nov 24 '22 15:11

oli_obk