Rust, Software Development

Rust E0384 Cannot Assign Twice To Immutable Variable

The E0384 error is one of the common errors programmers new to Rust will face. By default, variables are immutable in Rust. Having immutable variables helps up write concurrent codes and avoid common problems that come along with concurrency.

Sample Erring Codes

Consider the following codes. First, we declare and initialize a variable with 2. Then, we print the value. Finally, we attempt to change the variable’s value to 100. At this point, we get a compilation error.

The codes generate the following output. The error message tells us that we cannot modify the value of the variable i. Note that this is happening at compile-time, not at run-time. Therefore, it is the Rust compiler the threw the E0384 error and stopped the compilation. So, how do we fix this?

Fixing Rust E0384 Error On Variables

To fix the Rust E0384 error, we need to use the mut keyword between the let keyword and the variable name. Consider the following codes.

If we are to fix the previous codes, they would look as follows.

The new codes generate the following output.

So far we’ve tried primitive types. The Rust E0384 error can also happen when we change the properties of struct instances. Consider the following codes.

In the first scenario, we are instantiating a struct and assigning to the same variable on line 15. When run the codes, we get the following error.

We now know how to fix the Rust E0384 error and the correct codes as follows.

If we go back to the original codes and change one of the instance properties, we will get the same Rust E0384 error.

The codes generate the following error.

How to fix this? Simply use the mut keyword on the person variable.

Fixing Same Error On References

Variables that only hold references are also immutable, by default. Consider the following codes.

When the Rust compiler checks the codes, we get the following error.

How do we fix this? The correct codes are as follows.

In summary, variables in Rust are immutable, by default. To make variables mutable, we use the mut keyword.

This post is now part of Rust Programming Language For Beginners Tutorial.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like