Rust

Install Rust

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

Update Rust

rustup update


Compile and run

rustc src/test.rscargo buildcargo run (will compile and run main.rs)


Create new project

cargo new hello_world



User Input

use std::io;fn main {
  let mut guess String::new();
  io::stdin()
  .read_line(&mut guess)
  .expect("Failed to read line");
  println!("You guessed: {guess}");
}






Dependencies

install cargo pkgs

vi Cargo.toml
[dependencies]
rand = "0.8.3"

cargo build


Update dependencies
cargo update




Variables

new mutable string

let mut name = String::new()
name = "Joe"
name = "Frank"

Data Types

bool
char
f32,f64  // 32bit, 64bit float
i8,i16,i32,i64,i128 // signed int
i8 = -127 to 127
i16 =
u8,u16,u32,u64,u128 //unsigned 0 to 255, no negative




Integers

signed/unsigned integers (signed can be negative)

8 bit = i8 (-127 to 127), u8 (0 to 255)
16 bit = i16 (, u16 (-
32 bit = i32, u32
64 bit = i64, u64
128 bit = i128, u128
arch = isize, usize

floating point
f32, f64 (f64 is default)
let number = 2.0;

Tuple
fn main() {
  let tup: (i32, f64, u8) = (500, 6.4, 1);
}


convert String to Int

let mut guess = String::new();
guess = "23"



Math operations

fn main() {

  let sum = 5 + 10; // addition
  let difference = 95.5 - 4.3;   // subtraction
  let product = 4 * 30;   // multiplication
  let quotient = 56.7 / 32.2;   // division
  let floored = 2 / 3; // Results in 0
  let remainder = 43 % 5;   // remainder
}

Generate random # from 1-100
use rand::Rng
let secret: i32 = rand::thread_rng().gen_range(1..=100);