Published on

Learning Rust

Authors
  • avatar
    Name
    Chris Postma
    Twitter

I've had the desire to learn a new language lately. I originally was going to teach myself Go however I think Rust is the better choice for exploring new paradigms and helping me to think differently.

Usually when starting something new, my approach is to begin with some guided learning before mixing in self-directed learning and exploration. To that end, I will be completing two courses that I recently purchased on Udemy. The following are my notes from these courses.

Origin

  • Rust is a systems programming language that is pursuing safety, concurrency, and speed.
  • Ruby and Python will get you safety.
  • C/C++ will get you concurrency and speed but not safety.

Rust was started in 2006 by a Mozilla employee named Graydon Hoare. It was officially sponsored by Mozilla in 2009. Version 1 was released in 2015. Mozilla sponsored the language because they wanted something besides C++ to write FireFox in.

Cargo

Cargo is Rust's package manager. It is also the build system and test runner and documentation generator. It's like NPM, PIP, make, etc.

cargo new hello will create a new project.

  • Config files in Rust use the .toml extension, which stands for Tom's Obvious Minimal Language.
  • Rust files use the .rs extension.
  • cargo.toml is the config file for your project.

cargo run is the command to build and run your project. It will only recompile when changes exist.

  • Build artifacts are output to the target directory.
  • Add cargo run --release to compile your release mode code.

Basic syntax

Rust is a braced language with statement terminated by semicolons. Mimics C in particular.

fn main() {
  let bunnies = 2; // Inferred type
  let bunnies: i32 = 2; // Explicit type
  let (bunnies, carrots) = (8, 50); // Destructured variables for multiple variable initialization on single line
}

Variables are immutable by default.

  • Immutable variables by default help with safety, concurrency, and speed.
  • Safety because many bugs cannot occur if valeus never change.
  • Data that never changes can be shared between multiple threads without locks.
  • The compiler can do extra optimizations on immutable data to increase speed.

I can make a variable mutable by using mut:

let mut bunnies = 2;
const WARP_FACTOR: f64 = 9.9;

Constants cannot be mutable. These are inlined at compile time so they are very fast.

Scope

fn main() {
  let x = 5;
  {
    let y = 99;
    println!("{}, {}", x, y);
  }
  println!("{}, {}", x, y); // Error
}

There is no garbage collector, values are immediately dropped when they go out of scope.

Variables can also be shadowed by having the same variable in an inside scope.

Variables can also be shadowed in the same scope.

fn main() {
  let mut x = 5; // x is mutable
  let x = x; // x is now immutable
}

Memory safety