我的代码看起来像这样
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")
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个时,我得到了这个
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
Run Code Online (Sandbox Code Playgroud)
在寻找解决方案时,我遇到了这篇文章如何访问 `if let` 表达式之外的变量?但无法理解原因或其解决方案?
到目前为止,最简单的方法是对其进行编码,使其首先在范围内。您可以在单个赋值中将语句的结果赋值给变量。如果您可以将其制作为单行文字,那么它也可以说更具可读性。如果实际处理时间太长,没有什么可以阻止您只是......使其成为一个适当的功能。
let x = if int == 1 { "yes" } else { "no" };
// rest of the code accessing x.
Run Code Online (Sandbox Code Playgroud)
或者,如果您稍后正确分配变量,编译器将允许您声明未分配的变量,并进行所有编译时安全检查。阅读 RAII (Resource Acquisition Is Initialization) RAII Docs 上的文档以了解其工作原理的更多信息。在实践中,它就像这样简单:
let x;
if i == 1 {
x = "yes";
}
else {
x = "no";
}
// keep doing what you love
Run Code Online (Sandbox Code Playgroud)
如果存在未初始化 x 的逻辑路径,或者它被初始化为不同类型,编译器将出错。请注意,您也不需要将其声明为mut,因为它获得的第一个值将保持不变。除非你事后确实想改变它,显然。