Notes

rust

As of: 2024-06-23
skip editor formatting

#[rustfmt::skip]

allow

#![allow(warnings)]

Build for Release

cargo build --release

update rust compiler

rustup update

println!("{:b}", number)

padded print
println!("{:4}", some_val);
//output
"   8"
"  64"
" 512"
"1024"
snippets
// this modified the list
let foo = &mut list_list[index];
// changes are local to the block
let mut foo = list_list[index];
write to a file
use std::fs::File;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    {
        // opens a file for writing as well
        let mut file = File::create("test")?;
        // Write a slice of bytes to the file
        file.write_all(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])?;
    }

    {
        // open the file in read-only mode
        let mut file = File::open("test")?;
        // read the same file back into a Vec of bytes
        let mut buffer = Vec::<u8>::new();
        file.read_to_end(&mut buffer)?;
        println!("{:?}", buffer);
    }

    Ok(())
}
split strings
by separator
by new lines

s.lines

by regex
// use regex crate
let split:Vec<&str> = Regex::new(r"\s").unwrap().split("one two three")
- splits by space
- output: `["one", "two", "three"]`

Sort by
people.sort_by(|a, b| b.age.cmp(&a.age));
random
use base64::{engine::general_purpose, Engine as _};
use rand::{distributions::Alphanumeric, rngs::OsRng, thread_rng, Rng, RngCore};

fn option_1() -> String {
    let mut input = [0u8; 3];
    OsRng.fill_bytes(&mut input);
    general_purpose::URL_SAFE_NO_PAD.encode(input)
}
fn option_2() -> String {
    let rng = thread_rng();
    let uid: String = rng
        .sample_iter(&Alphanumeric)
        .take(6)
        .map(char::from)
        .collect();
    uid
}
fn option_3() -> String {
    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    const LENGTH: usize = 6;
    let mut rng = rand::thread_rng();

    let id: String = (0..LENGTH)
        .map(|_| {
            let idx = rng.gen_range(0..CHARSET.len());
            CHARSET[idx] as char
        })
        .collect();
    id
}
notes
Docmentation