Closed
Description
This fails:
fn print(b: bool, s1: &str, s2: &str) {
io::println(if b { s1 } else { s2 });
}
foo.rs:2:33: 2:39 error: mismatched types: expected `&/str` but found `&/str` (lifetime mismatch) foo.rs:2 io::println(if b { s1 } else { s2 }); ^~~~~~ foo.rs:1:38: 3:1 note: the anonymous lifetime #1 defined on the block at 1:38... [...] foo.rs:1:38: 3:1 note: ...does not necessarily outlive the anonymous lifetime #2 defined on the block at 1:38 [...]
while this works (giving the two borrowed pointers the same lifetime):
fn print(b: bool, s1: &r/str, s2: &r/str) {
io::println(if b { s1 } else { s2 });
}
as does this (not returning the pointers through if {} else {}):
fn print(b: bool, s1: &str, s2: &str) {
let mut s: &str;
if b { s = s1; } else { s = s2; }
io::println(s);
}
@nikomatsakis suggested the first example should work and that the type checker
should be content if the types of the two arms of the if{}else{}
expression
have a common supertype, rather than requiring them to be the same.