rust const generic is great for embedded system

76 points Trader-One 21 comments

const generic feature is not unique to rust. C++ templates have it, often called non-type template parameters. In C++ this feature is often overlooked because C++ is so bloated that programmers often do not know what all features C++ actually have.

In rust syntax is much less confusing than in C++. Its great feature for embedded development where every spared cpu cycle translates into longer battery life.

Small example:

// Generic over const bool B
fn log_B_state<const B: bool>(msg: &str) {
if B {
   println!("[DEBUG ACTIVE]: {}", msg);`
} else {
   println!("{}", msg);`
}
}

Calling function:

fn main() {
    // B must be known at compile time
    log_B_state::<true>("App is starting");
    log_B_state::<false>("Basic msg");
}