Why does the below code works fine in C but fails to compile in Rust?
#include <stdio.h>
int main(){
int a=30;
int* p=&a;
a+=10;//works fine in c
printf("%d",*p);//40
}
fn main() {
let mut a=30;
let b=&a;
a+=10;//doesnt compile
println!("{}",*b);
}
I'm a newbie to Rust and having trouble in understanding why cant we mutate the
variable a when we have a reference to it? Why is it designed in such way?
Race conditions, both single-threaded and multi-threaded.
A famous example of a single-threaded race condition is iterator invalidation, whereby mutating a container can re-allocate its backing buffer, resulting in invalid references.
Multi-threaded race conditions are a kind of obvious consequence – if you can't have multiple threads mutate the same variable at the same time, then data races are impossible by construction.
Preventing these kinds of bugs is basically one of the cornerstones of Rust design.
Here's a pre-Rust-1.0 article on the topic. Ignore the technical bits like mentions of @mut or &const (as those changed before stabilization), but read it for the higher-level points about aliasing, data races, and iterator invalidation.
And a quote from another post of Niko's:
Put another way, it’s become clear to me over time that the problems with data races and memory safety arise when you have both aliasing and mutability. The functional approach to solving this problem is to remove mutability. Rust’s approach would be to remove aliasing.