Declare a varialble in a if block and outlive it?

There is some log function that only makes sense when some N parameter is 2.

if N == 2 {
    let mut i = 0;
}

// Then later
if N == 2 {
    i += 1;
    println!("{}",i);
}

Problem is i's lifetime seems to be limited to the first if block, as the compilers complains that i not found in this scope. How can I deal with this?

Declare i outside the branch.

(But seriously, you can't do this. You can't use a potentially uninitialised variable, and you can't not use lexical scoping.)

3 Likes

Declare i outside the branch.

That's already my fix :slight_smile:

(But seriously, you can’t do this. You can’t use a potentially uninitialised variable, and you can’t not use lexical scoping.)

Thanks that was my actual question. I'm actually writing into a file, so I expected that it be created the first time and to keep the handle so that I don't need to fetch it in every other block, I might have over simplified in the op.

Well, that's different. You could use an Option<File>, and change the branches from N == 2 to let Some(f) = file.

2 Likes

Try Option.

Outliving the block could lead to use of an uninitialized variable.