DedSec Project

E0308 — DedSec Project

Rust E0308 — an expression has the wrong type Find the incompatible branch Rust branches producing a value need compatible types. An accidental semicolon converts a value expression into…

Rust E0308 — an expression has the wrong type

Find the incompatible branch

Rust branches producing a value need compatible types. An accidental semicolon converts a value expression into unit (), causing a mismatch with the declared return type.

fn classify(score: u8) -> &'static str {
    if score >= 50 { "pass" } else { "retry" }
}
fn main() {
    assert_eq!(classify(49), "retry");
    assert_eq!(classify(50), "pass");
}

The following deliberately broken function would yield a mismatch:

// fn broken() -> i32 {
//     let value = 3;
//     value; // semicolon returns unit (), not i32
// }

Repair the type contract

Read both sides of if, every match arm, the function return type, and the final block expression. Decide whether two string branches should return both borrowed &str values or both owned Strings. Do not use an unchecked cast simply to make the error disappear.

Independent exercise

Rewrite classify to return an enum with Pass and Retry variants, derive PartialEq and test scores 0, 49, 50, 100, 255. Compiler type correctness and business threshold correctness are separate requirements.

Official diagnostic: https://doc.rust-lang.org/error_codes/E0308.html

Diagnose the type of each branch

A frequent repair is to wrap both outcomes in the same algebraic type rather than forcing a cast:

fn parse_port(text: &str) -> Result<u16, &'static str> {
    match text.parse::<u16>() {
        Ok(value) if value > 0 => Ok(value),
        Ok(_) => Err("port must be nonzero"),
        Err(_) => Err("invalid decimal port"),
    }
}

Test "8080" as success, "0" as domain failure and "70000" as parse failure. An Ok(8080) arm and a bare "invalid" arm are incompatible: the latter must be Err(...). Keeping a typed error result is clearer than silencing a mismatch with unchecked numeric conversions. Also inspect the final expression: Ok(value); followed by no expression returns ().