Useful code snippet for debugging and while learning rust

When learning rust or debugging, you will certainly be using println! al lot!, also, you don't want to be annoyed by the compiler about the unused items. Sometimes also you want to know about the type of a variable.

So why not make a code snippet in your editor and make a keybinding to insert it in your rust files, this will save you some typing:

#![allow(unused)]
fn p<T: std::fmt::Debug>(v: &T) {
    println!("{:#?}", v);
}
fn t<T>(_: &T) {
    println!("{}", std::any::type_name::<T>());
}

use it:

fn main() {
    let var = 5;
    p(&var);
    t(&var);
}

You might want to make this a macro so that you can include more information such as line number in the case of t:

fn print_type<T>(_: &T, line: u32, file: &str) {
    println!("[{}:{}]: {}", file, line, std::any::type_name::<T>());
}

macro_rules! t {
    ($e:expr) => {
        {
            let x = $e;
            print_type(&x, line!(), file!());
            x
        }
    }
}

Playground


There is already a macro for p: dbg!, which has output like the t! macro I suggested:

dbg!(30);

Prints:

[src/main.rs:18] 30 = 30
5 Likes

@OptimisticPeach thanks for that, will be using dbg! instead!

1 Like