Rust (programming language)

From David's Wiki
\( \newcommand{\P}[]{\unicode{xB6}} \newcommand{\AA}[]{\unicode{x212B}} \newcommand{\empty}[]{\emptyset} \newcommand{\O}[]{\emptyset} \newcommand{\Alpha}[]{Α} \newcommand{\Beta}[]{Β} \newcommand{\Epsilon}[]{Ε} \newcommand{\Iota}[]{Ι} \newcommand{\Kappa}[]{Κ} \newcommand{\Rho}[]{Ρ} \newcommand{\Tau}[]{Τ} \newcommand{\Zeta}[]{Ζ} \newcommand{\Mu}[]{\unicode{x039C}} \newcommand{\Chi}[]{Χ} \newcommand{\Eta}[]{\unicode{x0397}} \newcommand{\Nu}[]{\unicode{x039D}} \newcommand{\Omicron}[]{\unicode{x039F}} \DeclareMathOperator{\sgn}{sgn} \def\oiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x222F}\,}{\unicode{x222F}}{\unicode{x222F}}{\unicode{x222F}}}\,}\nolimits} \def\oiiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x2230}\,}{\unicode{x2230}}{\unicode{x2230}}{\unicode{x2230}}}\,}\nolimits} \)

Rust is a low-level programming language.
The main advantage is that it encourages memory-safe programming through reference ownership and by isolating memory-unsafe functions.

Usage

Installation

See Install

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Syntax

Basics

// Const variable, must have type annotation.
const IMPORTANT_VALUE: i32 = 50;
fn main() {
  // C++: int x = 3;
  let mut x: i32 = 3;

  // Shadowing, creating a new variable.
  let x = x + 5;

  // Loop over values [0, 1, 2]
  for i in 0..3 {
    println!("This number is {}", i);
  }

  // Ternary is a single line if statement.
  let big_x = if x > 5 {x} else {5};
}

fn lerp(a: f64, b: f64, x: f64) -> f64 {
   // No semicolon implies return.
  (1.0 - x) * a + x * b
}

// Copied from rustlings.
pub fn fizz_if_foo(fizzish: &str) -> &str {
    if fizzish == "fizz" {
        "foo"
    } else if fizzish == "fuzz" {
        "bar"
    } else {
        "baz"
    }
}

Borrowing

This is like references or unique_ptr in C++.

let x = 5;
let mut y = 6;

// C++: const int &
example_borrow(&x)
// C++: int&
example_mut_borrow(&mut y)

Resources