This is a short ad of a Rust programming language targeting experienced C++ developers. Being an ad, it will only whet your appetite, consult other resources for fine print.
fn main() {
let mut xs = vec![1, 2, 3];
let x: &i32 = &xs[0];
xs.push(92);
println!("{}", *x);
}
This program creates a vector of 32-bit integers (std::vector<int32_t>
), takes a reference to the first element, x
, pushs one more number onto the vector and then uses x
. The program is wrong: extending the vector may invalidate references to element, and *x
might dereference a danging pointer.
The beauty of this program is that it doesn’t compile:
error[E0502]: cannot borrow xs as mutable
because it is also borrowed as immutable
--> src/main.rs:4:5
let x: &i32 = &xs[0];
-- immutable borrow occurs here
xs.push(92);
^^^^^^^^^^^ mutable borrow occurs here
println!(x);
- immutable borrow later used here
Rust compiler tracks aliasing status of every piece of data and forbids mutations of potentially aliased data. In this example, x
and xs
alias the first integer in the vector’s storage in the heap.
Rust doesn’t allow doing stupid things.
use crossbeam::scope;
use parking_lot::{Mutex, MutexGuard};
fn main() {
let mut counter = Mutex::new(0);
scope(|s| {
for _ in 0..10 {
s.spawn(|_| {
for _ in 0..10 {
let mut guard: MutexGuard<i32> = counter.lock();
*guard += 1;
}
});
}
}).unwrap();
let total: &mut i32 = counter.get_mut();
println!("total = {}", *total)
}
This program creates an integer counter protected by a mutex, spawns 10 threads, increments the counter 10 times from each thread, and prints the total.
#rust #developer