use std::fmt::Display;
fn label(flag: bool) -> impl Display {
if flag { 1 } else { "one" }
}
fn main() {
println!("{}", label(true));
}What happens when this is compiled?
- aIt compiles and prints
1; each branch is checked againstDisplayon its own. - bE0308: the
ifandelsebranches have incompatible types for the hidden type.✓ - cE0277:
&strdoes not implementDisplay, so only the1branch is valid. - dIt compiles and prints
one; the last expression fixes the concrete type.
Explanation:
impl Trait in return position is an opaque alias for a single concrete type chosen by the function body. Here one branch yields i32 and the other &str, so the compiler reports E0308 (if and else have incompatible types). Both types implement Display, so E0277 is not the issue. To return different types behind the same interface you need Box<dyn Display> and box each branch.