本页尚未翻译,以下为英文原文。
#E0041: branches of different types
The branches of an if or match, the breaks of a loop, or the return paths of a function without a written return type give values of different types. Nabi does not invent a sum type for them: annotate the slot with the sum, let v: i64 | str = if c { 1 } else { "a" };, write the return type (-> i64 | str), or make the branches agree. A branch that already is a sum counts by its members: when every other branch is that sum or one of its members, in any order, the result is that sum (none and i64 | none give i64 | none, str and i64 | str give i64 | str), but none and i64 still differ. An unsuffixed literal takes the other branches' type (if c { 1 } else { 2u8 } is u8; beside i32 | none it is i32), but an integer literal is never a float: write 1.0.
let c = true;
let v = if c { 1 } else { "one" };
error[E0041]: `if` branches have different types `i64` and `str` - Nabi does not infer a sum type; annotate the slot (`let v: i64 | str = if ...`) --> main.nabi:2:9 | 2 | let v = if c { 1 } else { "one" }; | ^^^^^^^^^^^^^^^^^^^^^^^^^
Annotate the variable with the sum type:
let c = true;
let v: i64 | str = if c { 1 } else { "one" };
println(f"{v is i64}");
true
A branch that already is the sum needs no annotation:
let c = false;
let r: i64? = 7;
let v = if c { none } else { r };
println(f"{v ?? 0}");
7
Related: E0040 mismatched types
Found a mistake? Edit this page on GitHub. Last updated