:: krowemoh

Friday | 27 DEC 2024
Posts Links Other About Now

previous
next

Rust Cheatsheet

2024-12-14

A quick rust starter.

Create a new project:

cargo new project_name

Printing

Print something:

let x = "World";
println!("Hello, {x}");

Print a rust structure:

let x = vec![1,2,3];
println!("Hello, {:?}", x);

Command line arguments

Get arguments:

use std::env;

let args: Vec<String> = env::args().collect();
println!("{:?}", args);

Find a flag:

if let Some(index) = args.iter().position(|a| a == "--flag") {
   args.remove(index);
   flag = true;
}

Exit a command line program:

use std::process;

process::exit(0);

Vectors

Get length of a vector:

let v = vec![1,2,3];

let len = v.len();

Files

Check if a file exists:

use std::path::Path;

Path::new(file_path).exists()

Read a file:

use std::fs;

let content = fs::read_to_string(file_path).expect("Failed to read.");