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.

First Program

fn main() {
  let mut xs = vec![1, 2, 3];
  let x: &i32 = &xs[0];
  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/

     let x: &i32 = &xs[0];
                    -- immutable borrow occurs here
     ^^^^^^^^^^^ mutable borrow occurs here
              - 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.

Second Program

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;

  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

Two Beautiful Rust Programs
1.85 GEEK