Rod*_*igo 1 scope if-statement variable-declaration rust
在 Go 中,我们可以在表达式的条件中声明变量if。该变量在作用域内有效if,在作用域外无效。例如:
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!
}
Run Code Online (Sandbox Code Playgroud)
Rust 中有类似的语法吗?
Rust 确实有if let表达式:
if let n = 4 {}
println!("{}", n); // error: cannot find value `n` in this scope
Run Code Online (Sandbox Code Playgroud)
这些主要用于模式匹配:
let optional_num = Some(1);
if let Some(num) = optional_num {
println!("optional_num contained", num);
} else {
println!("optional_num was None");
}
Run Code Online (Sandbox Code Playgroud)
有一个if let 链的RFC允许这样的事情:
if let n = 4 && n != 0 {
println!("{} is not zero", n);
}
println!("{}", n); // error, n doesn't exist here!
Run Code Online (Sandbox Code Playgroud)
但是,链中声明的变量的范围if let仅限于if语句,而不是else,因此您的示例是不可能的:
if let n = 4 && n != 0 {
println!("{} is not zero", n);
} else {
println!("{}", n); // error, n doesn't exist here!
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3494 次 |
| 最近记录: |