如何访问范围之外的rust变量?

时间:2020-01-26 10:06:08

标签: scope rust

我的代码如下

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")
    }
}

当我运行它时,我得到了

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

在寻找解决方案时,我遇到了这篇帖子How do I access a variable outside of an `if let` expression?,但无法理解其原因或解决方案?

4 个答案:

答案 0 :(得分:5)

到目前为止,最简单的方法是对它进行编码,以使其放在第一位。 您可以在单个赋值中将变量与语句的结果赋值。 如果您可以将它作为单行代码使用,那么它也可以说更具可读性。 如果实际处理时间过长,那么什么也不会阻止您...使其正常工作。

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

或者,如果以后适当分配它们,则编译器将让您声明未分配的变量,并进行所有编译时安全检查。阅读有关RAII(资源获取即初始化)RAII Docs的文档,以了解其工作原理。实际上,它就是这样简单:

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

如果存在未初始化x的逻辑路径,或者如果将其初始化为其他类型,则编译器将出错。 请注意,您也无需将其声明为mut,因为它获取的第一个值将保持不变。显然,除非您以后确实希望更改它。

答案 1 :(得分:1)

您无法访问超出范围的变量。但是,您可以使用一种解决方法,并将变量设置在相同的范围内。

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

    if x == "yes" {
        println!("yes");
    } else if x == "no" {
        println!("no");
    }
}

答案 2 :(得分:0)

问题

我相信您是在问该错误是什么意思

要回答这个问题,必须首先回答什么是范围

答案

从广义上讲,作用域是存在变量的代码部分。

因此,如果错误提示在此范围内未找到 ,则表示该变量在此处不存在。

示例

fn main() {
    let a_bool = true;
    let main_scope_x = 0;

    if a_bool == true {
        let if_scope_x = 1;
    } // if_scope_x stops existing here!

    println!("main x has the value {}", main_scope_x);
    println!("if x has the value {}", if_scope_x); // this will cause an error, if_scope_x does not exist outside the if expression.
}

更多信息

https://doc.rust-lang.org/stable/book/ch04-01-what-is-ownership.html (读这本书!很好!)

答案 3 :(得分:0)

在Rust中,每个变量都有一个范围,该范围从初始化变量的地方开始。在遇到问题时,您尝试使用在xif int == 1内部创建的变量if x == "yes",因为如果语句的作用域与函数main分开,则不能在if语句内创建一个变量,并希望在离开范围时不会将其清除。最简单的解决方案是将变量x初始化为您想在if x == "yes"中使用的变量,因此 let 说我们想要x的范围通过将main放在let x;中以从main开始。在Rust中,可能会有较大范围的变量对较大范围内的变量可见,而该较大范围内的变量已初始化,因此从if语句的范围内分配变量是完全有效的。

有关更多信息,请查看https://doc.rust-lang.org/rust-by-example/variable_bindings/scope.html

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

但是您可以摆脱两个if语句,而只需使用match:

fn main() {
    let myint = 1;

    match myint {
        1 => {println!("yes")}
        _ => {println!("no")}
    }
}