A reliability guard can reject invalid input before the expensive path runs, keeping outputs explicit.

Program

Play the program to choose an input and see the cached-style result string.

cache_result_guard.rs
fn main() {
    let input = ;
    let cached = cached_square(input);
    println!("{cached}");
}

fn cached_square(value: i32) -> String {
    if value < 0 {
        "invalid".to_string()
    } else {
        let squared = value * value;
        format!("square={squared}")
    }
}
fn main() {
    let input = ;
    let cached = cached_square(input);
    println!("{cached}");
}

fn cached_square(value: i32) -> String {
    if value < 0 {
        "invalid".to_string()
    } else {
        let squared = value * value;
        format!("square={squared}")
    }
}
fn main() {
    let input = ;
    let cached = cached_square(input);
    println!("{cached}");
}

fn cached_square(value: i32) -> String {
    if value < 0 {
        "invalid".to_string()
    } else {
        let squared = value * value;
        format!("square={squared}")
    }
}
guard The negative-input branch exits before doing the square calculation.
stable result Both success and rejection paths return a string the caller can print.
cache shape The function isolates result construction behind one call site.