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.

input
cache_result_guard.rs
Replay: real traced execution (multi-file project)
fn main() {
    let input = 4;
    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 = -1;
    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 = 7;
    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}")
    }
}
  1. input ← 4

    1fn main() {2    let inpu→ 4t = 4; //@input=4, 7, -13    let cached = cached_square(inpu4t);4    println!("{cached}");
  2. squared ← 16

    9        "invalid".to_string()10    } else {11        let square→ 16d = valu4e * value;12        format!("square={squared}")13    }14}
  3. cached ← "square=16"

    2    let input = 4; //@input=4, 7, -13    let cache→ "square=16"d = cached_square(inpu4t);4    println!("{cached}");5}
    outputsquare=16
  1. input ← -1

    1fn main() {2    let inpu→ -1t = -1;3    let cached = cached_square(inpu-1t);4    println!("{cached}");
  2. if value < 0

    7fn cached_square(value: i32) -> String {8    if valu-1e < 0 {9        "invalid".to_string()10    } else {11        let squared = value * value;
  3. cached ← "invalid"

    2    let input = -1;3    let cache→ "invalid"d = cached_square(inpu-1t);4    println!("{cached}");5}
    outputinvalid
  1. input ← 7

    1fn main() {2    let inpu→ 7t = 7;3    let cached = cached_square(inpu7t);4    println!("{cached}");
  2. squared ← 49

    9        "invalid".to_string()10    } else {11        let square→ 49d = valu7e * value;12        format!("square={squared}")13    }14}
  3. cached ← "square=49"

    2    let input = 7;3    let cache→ "square=49"d = cached_square(inpu7t);4    println!("{cached}");5}
    outputsquare=49
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.