Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access rust variables outside the scope?

Tags:

scope

rust

My code look like this

fn main() {
    // some other codes goes here
    let int = 1;
    if int == 1 {
        let x = "yes";
    } else {
        let x = "no";
    }
    if x == "yes" {
        // some other codes goes here
        println!("yes");
    } else if x == "no" {
        // some other codes goes here
        println!("no")
    }
}

When I run this I get this

error[E0425]: cannot find value `x` in this scope
 --> src/main.rs:9:8
  |
9 |     if x == "yes" {
  |        ^ not found in this scope

error[E0425]: cannot find value `x` in this scope
  --> src/main.rs:12:15
   |
12 |     } else if x == "no" {
   |               ^ not found in this scope

While searching for a solution I came across this post How do I access a variable outside of an `if let` expression? but could not able to understand the reason or its solution?

like image 752
Eka Avatar asked Nov 15 '25 23:11

Eka


2 Answers

Easiest is by far to code it such that it is in scope in the first place. You can assign variable with the result of a statement in a single assignment. If you can make it as a one-liner, it also makes it arguably more readable. If the actual processing is too long, nothing prevents you from just... making it a proper function.

let x = if int == 1 { "yes" } else { "no" };
// rest of the code accessing x.

Alternatively, the compiler will let you declare unassigned variables if you properly assign them later, with all the compile-time safety checks in place. Read the docs on RAII (Resource Acquisition Is Initialization) RAII Docs to see more how it works. In practice, it's just as simple as this:

let x;
if i == 1 {
    x = "yes";
}
else {
    x = "no";
}
// keep doing what you love

The compiler will error if there's a logic path where x doesn't get initialized, or if it gets initialized as a different type. Notice you also do not need to declare it as mut, as the first value it gets will stay immutable. Unless you do want to change it afterwards, obviously.

like image 56
LotB Avatar answered Nov 18 '25 19:11

LotB


You can't access a variable which is out of scope. But you use a workaround and set the variable in the same scope.

fn main(){
    let int = 1;
    let x = if int == 1 {
        "yes"
    } else {
        "no"
    };

    if x == "yes" {
        println!("yes");
    } else if x == "no" {
        println!("no");
    }
}
like image 28
Ejdrien Avatar answered Nov 18 '25 20:11

Ejdrien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!