Skip to content

if b { x } else { y } requires identical types for x and y #4025

Description

@ben0x539

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions