rodrigocfd
rodrigocfd

Reputation: 8078

Is it possible to declare a variable in the conditional of an if expression in Rust?

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?

Upvotes: 1

Views: 4108

Answers (3)

Shepmaster
Shepmaster

Reputation: 432199

You can always define a new scope using curly braces:

fn main() {
    {
        let n = 4;
        if n != 0 {
            println!("{} is not zero", n);
        } else {
            println!("{} is zero", n);
        }
    }
    
    println!("{}", n); // error, n doesn't exist here!
}

If you felt strongly enough about it, you could wrap that in a macro:

macro_rules! thing {
    ($($s:stmt);+ , $e:expr) => {{
        $($s)+
        $e
    }};
}

fn main() {
    thing!(let n = 4, if n != 0 {
        println!("{} is not zero", n);
    } else {
        println!("{} is zero", n);
    });
    
    println!("{}", n); // error, n doesn't exist here!
}

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

I feel like what you're trying to do in your code more closely aligns with a match statement. Something like this:

match 4 {
    n @ 0 => {
        println!("{} is zero", n);
    },
    
    n => {
        println!("{} is not zero", n);
    }
}

Or, more generically, if you want to test some arbitrary boolean expression based on n:

match some_expression {
    n if some_boolean_function(n) => {
        println!("{} meets the requirements", n);
    },
    
    n => {
        println!("{} does not meet the requirements", n);
    }
}

Upvotes: 2

Ibraheem Ahmed
Ibraheem Ahmed

Reputation: 13628

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! 
}

Upvotes: 5

Related Questions