如何在作用域外访问Rust变量?

4

我的代码长这样

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

我在寻找解决方法时发现了这篇帖子《如何访问if let表达式之外的变量?》,但我无法理解其原因或解决方案。

4个回答

8
最简单的方法是在编码时将其设为范围内。 您可以使用单个赋值语句将变量分配为语句的结果。 如果可以将其作为一个一行代码,这也使它更易读。 如果实际处理过程太长,您可以将其转换为适当的函数。
let x = if int == 1 { "yes" } else { "no" };
// rest of the code accessing x.

或者,编译器会允许您声明未分配的变量,如果您稍后正确地分配它们并保留所有编译时安全检查。阅读 RAII(资源获取即初始化)RAII文档 以了解更多信息。在实践中,它就像这样简单:

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

如果存在逻辑路径未对 x 进行初始化或其以不同类型进行初始化,则编译器将报错。

请注意,您也无需声明它为 mut,因为它获取的第一个值将保持不可变。当然,除非您之后确实需要更改它。


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

0
在Rust中,每个变量都有一个作用域,该作用域从初始化变量的地方开始。在你的问题中,你尝试使用变量x,该变量是在if int == 1if x == "yes"内部创建的。由于if语句具有与函数main不同的作用域,因此您不能在if语句内部创建变量并期望它在离开作用域时不被清除。最简单的解决方案是在您想要在if x == "yes"中使用该变量的位置初始化变量x,所以让我们假设我们希望变量xmain中启动作用域,通过在main中放置let x;来实现。在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")}
    }
}

-1

问题

我相信你在问“这个错误是什么意思?”

要回答这个问题,首先必须回答“什么是作用域?”

答案

作用域,通俗地说,是变量存在的代码段。

因此,当错误提示说“在此作用域中未找到”,它意味着该变量在此处不存在。

一个例子

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 (阅读这本书吧!非常好!)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接