Rust

description: Rust Programming Language - Low level language

lang: ENG

Basics

Syntax

Comments

// Rust use only the one line comment
// so you don't have to worry about various
// styles!

Main

fn main() {
    // Program
}

Imports

use std::io;

Constants and variables

let x = 5;
let x = 6;
// Forbidden: x = 6
let mut x = 5;
x = 6;
const I_AM_A_CONSTANT: u32 = 42;

Tuples

let tuple: (i32, f32, bool, char) = (500, 6.4, true, 'a');
let (i,f,b,c) = tuple; // Deconstruction
let f = tuple.1; // Field access

Arrays

let x = [1,2,3,4,4];
let x: [i32; 5] = [1,2,3,4,4];
let x = [4; 5]; // = [4, 4, 4, 4, 4];
let first = x[0];

Functions

fn function_name(arg: i32) -> i32 {
    return arg + 2;
}

Printing

let x = 1;
let y = 2;

println!("x = {x}, y = {}", y);

Pattern matching

let x = match res {
    Ok(num) => num,
    Err(_) => continue,
}

If-then-else

if boolean_expression {
    // Case one!
} else if another_expression {
    // Another case!
} else {
    // Final case!
}

Loop

loop {
    // Need a break; to leave this loop.
}
let mut counter = 0;
let result = loop {
    counter += 1;
    if counter == 10 {
        break counter * 2;
    }
};
'label: loop {
    break 'label;
}
let mut number = 10;
while number != 0 {
    number -= 1;
}
for element in collection {
    // Do something.
}
for number in (0..4) {
    // Do something too.
}

Cmdline

Rustc

rustc file.rs
./file

Cargo

Create a new project

cargo new <project_name>

Build a project

cargo build

Build and run a project

cargo run

Check the code is correct

cargo check

Resources

Library docs

Learning