'Evaluate if only on startup

consider the following example:

use std::fs;
use std::path::Path;

fn get_battery() -> String {
    let power = if Path::new("/sys/class/power_supply/BAT0/power_now").exists() {
        fs::read_to_string("/sys/class/power_supply/BAT0/power_now")
            .expect("Error BAT0/power_now")
            .trim()
            .parse::<f32>()
            .unwrap()
            / f32::powi(10.0, 6)
    } else {
        let current = fs::read_to_string("/sys/class/power_supply/BAT0/current_now")
            .expect("Error BAT0/current_now")
            .trim()
            .parse::<f32>()
            .unwrap()
            / f32::powi(10.0, 6);
        let voltage = fs::read_to_string("/sys/class/power_supply/BAT0/voltage_now")
            .expect("Error BAT0/voltage_now")
            .trim()
            .parse::<f32>()
            .unwrap()
            / f32::powi(10.0, 6);
        current * voltage
    };

    return power.to_string()
}

fn main() {

    loop {
        std::thread::sleep(std::time::Duration::from_secs(1))
        println!("{}", get_battery());
    }
}

I would like to evaluate the if statement, inside the get_battery function, once on startup and follow that branch (read power or read current/voltage) in the successive function call.

Is there a way to instuct the compiler to compile two versions of the same function and run the right one based on the existence of a file on startup?

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source