Rust error: cannot assign twice to immutable variable
Created
Modified
Variables Immutable
You can make them mutable by adding mut in front of the variable name. For example,
fn main() {
let x = 2;
println!("value x: {}", x);
x = 4;
println!("value x: {}", x);
}
error[E0384]: cannot assign twice to immutable variable `x` --> src/main.rs:5:3 | 2 | let x = 2; | - | | | first assignment to `x` | help: consider making this binding mutable: `mut x` ... 5 | x = 4; | ^^^^^ cannot assign twice to immutable variable For more information about this error, try `rustc --explain E0384`. error: could not compile `hello-rust` due to previous error
Save and run the program using cargo run. You should receive an error message.
Variables Mutable
When a variable is immutable, once a value is bound to a name, you can’t change that value. For example,
fn main() {
let mut x = 2;
println!("value x: {}", x);
x = 4;
println!("value x: {}", x);
}
value x: 2 value x: 4
Mismatched Types
For example,
fn main() {
let mut s = "abcd";
// mutate a variable’s type
s = s.len()
}
error[E0308]: mismatched types --> src/main.rs:3:7 | 2 | let mut s = "abcd"; | ------ expected due to this value 3 | s = s.len() | ^^^^^^^ expected `&str`, found `usize` For more information about this error, try `rustc --explain E0308`. error: could not compile `hello-rust` due to previous error