In Go, we can declare a variable inside the conditional of an if
expression. This variable will be valid inside the if
scope, and not outside of it. For example:
func main() {
if n := 4; n != 0 {
fmt.Printf("%d is not zero", n)
} else {
fmt.Printf("%d is zero", n)
}
fmt.Printf("%d", n) // error, n doesn't exist here!
}
Is there a similar syntax in Rust?
Rust does have if let
expressions:
if let n = 4 {}
println!("{}", n); // error: cannot find value `n` in this scope
These are primarily used for pattern matching:
let optional_num = Some(1);
if let Some(num) = optional_num {
println!("optional_num contained", num);
} else {
println!("optional_num was None");
}
There is an RFC for if let chains that would allow for something like this:
if let n = 4 && n != 0 {
println!("{} is not zero", n);
}
println!("{}", n); // error, n doesn't exist here!
However, the variables declared in if let
chains are scoped only to the if
statement, not the else
, so your example would not be possible:
if let n = 4 && n != 0 {
println!("{} is not zero", n);
} else {
println!("{}", n); // error, n doesn't exist here!
}